Create Custom WooCommerce Product Tabs with Advanced Custom Fields

 When viewing a product in WooCommerce information about the product is displayed in tabs. These tabs are fixed and generated by WooCommerce, outside your control. This post will show you how add code that allow the authors to add custom tabs with custom content to products.

Disclaimer: There is a WooCommerce extension called WooCommerce Tab Manager which provides this feature. It’s not free, though. I have not tested it myself, but as far as I can see it only supports a WYSIWYG (what you see is what you get) editor for the tab contents. This post is for you who want more finetuning of the tab contents or want to write the code yourself without paying for another plugin.

We will use the plugin Advanced Custom Fields (ACF) to simplify the process. But you should be able to quite easily replace ACF’s part with your own custom code if you don’t wish to use the plugin. ACF comes in a free version and a Pro version. In ACF Pro there’s a nifty field type: the repeater, which is perfect for this kind of use. If you however don’t have or wish to purchase a Pro license, don’t worry. The code tutorial below will show you how to add fields using both the free version – and using the repeater in Pro version.

If you are not already familiar with ACF, what ACF helps us with is easy setup of post meta fields – of all kinds. You can easily add an editor, a file picker, date- or colorpicker, a post or category selector with support for multiple choices and reordering, and more. We can achieve the same without ACF but then we would need to code the display and saving of metaboxes content ourselves.

What we will make

To put it simply we want to allow adding custom tabs to product view. Each tab supports a title that is displayed as tab label, and the content that is displayed when clicking on the tab. The custom tabs really depend on the type of project or needs you have; maybe you need tabs for technical specs, a tab with files (e.g. user manuals and such), additional information, or a custom query that displays related products.

In this tutorial we will keep it simple by adding a WYSIWYG editor for the tab contents. As mentioned above it’s easy to implement other field types (e.g. files or a post query), it’s just a difference in the code you write for displayed the tab contents – which is unrelated to this tutorial.

If you have ACF Pro and want to use the repeater for easily adding multiple tabs; skip over the next section. If you only have the free version of ACF, continue on. The disadvantage of not having the repeater field is that you need to define a fixed number of tabs. So the author cannot make unlimited number of tabs as they can with the repeater. But this free solution will work just fine in webshops where you just want specific (number of) custom tabs.

Tutorial for ACF free version

Adding the ACF fields

Adding a new metabox with fields in it is really easy with ACF. You have two options; use ACF’s UI to set up everything, or add the fields by code. Usually setting the fields up in admin is the way to go. But if you need to ensure the fields exist in multiple WordPress sites (e.g. localhost development, test server and live server) you might benefit adding the fields by code in your theme or plugin.

You need to set up the following:

  • A group that displays when the post type equals WooCommerce products
  • A text input for the tab title
  • Whatever field(s) you want for the tab contents. As an example we’ll add a WYSIWYG editor.
  • (Optional) Additional tab titles and tab contents for as many tabs we want to support.

Please take note to remember the field names as you’ll need to refer to them later. I’ve defined the tab title as tab_title and the WYSIWYG field as tab_contents.

If you’d rather add the fields by code, here’s an example. Add this in your theme’s functions.php or plugin file:

  1. if (class_exists('acf')) {
  2. add_action('acf/init', function() {
  3. $fields = [
  4. [
  5. 'key' => 'field_tab_title',
  6. 'label' => __('Custom tab title', 'txtdomain'),
  7. 'name' => 'tab_title',
  8. 'type' => 'text',
  9. ],
  10. [
  11. 'key' => 'field_tab_contents',
  12. 'label' => __('Custom tab content', 'txtdomain'),
  13. 'name' => 'tab_contents',
  14. 'type' => 'wysiwyg',
  15. 'tabs' => 'all',
  16. 'toolbar' => 'full',
  17. 'media_upload' => 1,
  18. 'delay' => 0,
  19. ],
  20. ];
  21.  
  22. acf_add_local_field_group([
  23. 'key' => 'group_custom_woocommerce_tabs',
  24. 'title' => __('Custom Tabs', 'txtdomain'),
  25. 'fields' => $fields,
  26. 'label_placement' => 'top',
  27. 'menu_order' => 0,
  28. 'style' => 'default',
  29. 'position' => 'normal',
  30. 'location' => [
  31. [
  32. [
  33. 'param' => 'post_type',
  34. 'operator' => '==',
  35. 'value' => 'product'
  36. ]
  37. ]
  38. ],
  39. ]);
  40. });
  41. }

If you want more than just one tab, just add another set of tab title and tab contents after line #19. Just remember to keep name unique.

When we edit a product we should see this metabox appear:

Outputting your custom tabs

WooCommerce allows us to filter woocommerce_product_tabs for manipulating tabs. As argument to this filter you get an array for all tabs. The array consists of arrays for each tab with unique keys. But the array for each tab does not contain the actual output of the tab contents. Instead it expects a callback – a name of a function that WooCommerce will run for outputting the tab contents.

Once inside the function you can use global $post to get access to the current post object, or if you want the product object WooCommerce generates, simply do global $product. We need the post ID in order to fetch the value of our custom fields with ACF’s function get_field(). In the code example below we are only fetching the tab title and checks if this is empty or not. If it’s not, then it adds a new tab to the array. It makes sense to not add tabs where the tab title is empty.

  1. if (class_exists('acf') && class_exists('WooCommerce')) {
  2. add_filter('woocommerce_product_tabs', function($tabs) {
  3. global $post, $product; // Access to the current product or post
  4. $custom_tab_title = get_field('tab_title', $post->ID);
  5.  
  6. if (!empty($custom_tab_title)) {
  7. $tabs['awp-' . sanitize_title($custom_tab_title)] = [
  8. 'title' => $custom_tab_title,
  9. 'callback' => 'awp_custom_woocommerce_tabs',
  10. 'priority' => 10
  11. ];
  12. }
  13. return $tabs;
  14. });
  15.  
  16. function awp_custom_woocommerce_tabs($key, $tab) {
  17. global $post;
  18.  
  19. ?><h2><?php echo $tab['title']; ?></h2><?php
  20.  
  21. $custom_tab_contents = get_field('tab_contents', $post->ID);
  22. echo $custom_tab_contents;
  23. }
  24. }

Note that you can use ‘priority‘ to control the tab’s position. For example setting it to 1 will make your tab appear first, before all of WooCommerce’s tabs. Define a function name to the ‘callback‘ element. In line #17 we define the function that WooCommerce will run for outputting the tab content.

These tab callback functions will get two parameters; the key and the array element of all values for the current tab. Inside our callback function we output the tab title again, by referring to the provided $tab array. WooCommerce echoes their tab titles inside a h2 so we just do the same. And then we use get_field() to get the value of the tab contents and simply echo the value. Adjust line #23 to fit whatever kind of field types you’ve added (e.g. post object selector, images, or something else).

Note that I have wrapped everything inside an if-check that checks whether or not both WooCommerce and ACF is activated. This is good practice to prevent your site from breaking.

And that’s it! You have now successfully created code to add custom WooCommerce tabs!

If you want to do this with ACF Pro’s repeater field to support unlimited number of tabs, read on.

Tutorial for ACF Pro and repeater

Adding the ACF fields

Add your group using either ACF’s admin UI or adding them by code in your theme or plugin files. We need to set up the following:

  • A group that displays when the post type equals WooCommerce product
  • A repeater with the following sub fields:
    • A text input for the tab title
    • Whatever field(s) you want for the tab contents.

This is how you would set it up using ACF admin:

Or you can add the group by code like so:

  1. if (class_exists('acf')) {
  2. add_action('acf/init', function() {
  3. $fields = [
  4. [
  5. 'key' => 'field_custom_tabs_repeater',
  6. 'label' => __('Custom tabs', 'txtdomain'),
  7. 'name' => 'custom_tabs_repeater',
  8. 'type' => 'repeater',
  9. 'layout' => 'row',
  10. 'button_label' => __('Add new tab', 'txtdomain'),
  11. 'sub_fields' => [
  12. [
  13. 'key' => 'field_tab_title',
  14. 'label' => __('Tab title', 'txtdomain'),
  15. 'name' => 'tab_title',
  16. 'type' => 'text',
  17. ],
  18. [
  19. 'key' => 'field_tab_contents',
  20. 'label' => __('Tab content', 'txtdomain'),
  21. 'name' => 'tab_contents',
  22. 'type' => 'wysiwyg',
  23. 'tabs' => 'all',
  24. 'toolbar' => 'full',
  25. 'media_upload' => 1,
  26. 'delay' => 0,
  27. ],
  28. ],
  29. ],
  30. ];
  31.  
  32. acf_add_local_field_group([
  33. 'key' => 'group_custom_woocommerce_tabs',
  34. 'title' => __('Custom Tabs', 'txtdomain'),
  35. 'fields' => $fields,
  36. 'label_placement' => 'top',
  37. 'menu_order' => 0,
  38. 'style' => 'default',
  39. 'position' => 'normal',
  40. 'location' => [
  41. [
  42. [
  43. 'param' => 'post_type',
  44. 'operator' => '==',
  45. 'value' => 'product'
  46. ]
  47. ]
  48. ],
  49. ]);
  50. });
  51. }

Either way you should end up with this metabox when editing products:

Outputting your custom tabs

Outputting your custom tabs is very similar to what we did above in for the free version. We filter woocommerce_product_tabs, but here we loop through each repeated item from the repeater. We need a way to identify each element in the repeater with keys, so we generate a key ourselves by using the loop position and a slug-version of the tab title. In the callback function we extract the loop position from the key and use this to refer to the array for our repeater.

  1. if (class_exists('acf') && class_exists('WooCommerce')) {
  2. add_filter('woocommerce_product_tabs', function($tabs) {
  3. global $post, $product; // Access to the current product or post
  4. $custom_tabs_repeater = get_field('custom_tabs_repeater', $post->ID);
  5.  
  6. if (!empty($custom_tabs_repeater)) {
  7. $counter = 0;
  8. $start_at_priority = 10;
  9. foreach ($custom_tabs_repeater as $custom_tab) {
  10. $tab_id = $counter . '_' . sanitize_title($custom_tab['tab_title']);
  11. $tabs[$tab_id] = [
  12. 'title' => $custom_tab['tab_title'],
  13. 'callback' => 'awp_custom_woocommerce_tabs',
  14. 'priority' => $start_at_priority++
  15. ];
  16. $counter++;
  17. }
  18. }
  19. return $tabs;
  20. });
  21.  
  22. function awp_custom_woocommerce_tabs($key, $tab) {
  23. global $post;
  24.  
  25. ?><h2><?php echo $tab['title']; ?></h2><?php
  26.  
  27. $custom_tabs_repeater = get_field('custom_tabs_repeater', $post->ID);
  28. $tab_id = explode('_', $key);
  29. $tab_id = $tab_id[0];
  30.  
  31. echo $custom_tabs_repeater[$tab_id]['tab_contents'];
  32. }
  33. }

Inside our filter function we fetch the value of the repeater and checks if it’s not empty. We then define a counter variable, starting at 0 (arrays always start with position 0), which we increment with 1 for each element inside the loop (at line #18). In the loop for each repeater item we assign them all to the same callback function. We use WordPress’ function sanitize_title() to convert the tab title into a slug version of it, and appends it to the key.

In our callback function at line #31 - 32 we do some simple string manipulations to extract the counter value (which starts at 0 and increments by 1 for each item). We then simply use this as the index for the repeater array in order to fetch the correct tab content field.

Mới hơn Cũ hơn