miguel.nz

Additional product tabs on Woocommerce using ACF

April 25, 2020   |   1 minute read.

I wanted to add additional product tabs on Woocommerce using Advanced Custom Fields. The repeater feature which comes from ACF PRO can be a great help.

Before digging into this small tutorial:

  • You have ACF and the repeater field type
  • You know how to add repeater fields and link them into the product post type

Let’s say we have a repeater field with the following array from a repeater field called product_tab:

array(2) {
  [0]=>
  array(2) {
    ["title"]=> string(8) "Cuidados"
    ["content"]=> string(43) "Woocommerce tabs using ACF"
  }
  [1]=>
  array(2) {
    ["title"]=> string(13) "Otra pestaƱa"
    ["content"]=> string(25) "Custom fields are great!"
  }
}

Once we get our content, then we need to use the woocommerce_product_tabs:

class ALM_ProductTabs {
  function __construct() {
    global $post;
    // Exit if is not a product template
    if (!is_singular( 'product' )) {
      return false;
    }
    // We get the field product_tab field
    $this->product_tab = get_field( 'product_tab' );
    if($this->product_tab) {
      // Adding the filter
      add_filter( 'woocommerce_product_tabs', array($this, 'add_product_tab') );
    }
  }

  public function add_product_tab($tabs) {
    foreach ($this->product_tab as $key => $item) {
      $slug = sanitize_key($item['title'] . '-' . $key);
      $tabs[$slug] = array(
        // The title tab
        'title'     => $item['title'],
        'priority'  => 50,
        // Call back to add the content inside the tab
        'callback'  => function() use($item){
          echo apply_filters( 'the_content', $item['content'] );
        }
      );
    }
    return $tabs;
  }

}

add_action('template_redirect', function(){
  new ALM_ProductTabs();
}, 5);

Save this into your functions.php and you should be all good to go.