In eCommerce, we usually see a product that has a bunch of different variations. For example, a T-shirt may have different colors along with different information such as size and price, then each one will be a variation.

Today, we are going to display them all in a clever way on the single product page. Whenever you click on a color button, all the corresponding information of that variation will be displayed, even in the image gallery.

The example of displaying product variations on the single product page

To do that, we need some particular techniques. In this practice, we’ll use custom fields created by Meta Box. By the way, we do not use any theme, just Gutenberg here.

Before Getting Started

To add all of the extra information for variations, we need custom fields. So, the first tool on the list is Meta Box core plugin. This is the framework to create custom fields & custom post types. It’s free and available on wordpress.org. We also use some advanced features of Meta Box by using the following extensions:

  • MB Custom Post Type & Custom Taxonomies: It’s a free extension of Meta Box to create custom post types.
  • Meta Box Builder: This premium extension provides a UI in the back end to create custom fields easily.
  • Meta Box Conditional Logic: It lets you show fields precisely as any rules you want.
  • Meta Box Group: This extension helps you organize custom fields into repeatable and collapsible groups.
  • MB Views: It helps you to create templates without touching the theme files as well as get the custom fields’ value and display them.

Video Tutorial

Step 1: Create a New Custom Post Type

Go to Meta Box > Post Types > New Post Type. After creating a new post type, you will see a new menu appears on your dashboard. It’s your new post type.

 creating a new post type.

Step 2: Create Custom Fields

Go to Meta Box > Custom Fields > Add New.

Create custom fields by Meta Box.

We have a tutorial on how to create custom fields, you can refer to it for more information.

This is the structure of the fields that I’ll create.

Field Types of Field ID
Does This Product Have Variations? Switch Does_this_product_have_variaitons
Simple Product Group simple_product
          Product Image Image Advanced product_image
          Size Checkbox List size
          Original Price Text original_price
          Promotional Price Text promotional_price
          Status Select status
Variations of Product Group variations_of_product
          Product Image Image Advanced product_image
          Size Checkbox List size
          Original Price Text original_price
          Promotional Price Text promotional_price
          Status Select status
          Color Name Select color_name

As you can see here, I have a Switch field to confirm whether the product has variations or not. If your product doesn’t have any variation, it is a simple product, so the Simple Product group will be displayed for inputting data.

Then, there is some basic information that we put in that group with subfields inside.

Simple Product group with subfields inside

If the product has any variations, the Variations of Product group will be displayed. This group also has subfields similar to the Simple Product group. In addition, it has an extra subfield inside to define the name of the variation which is Color Name.

To set the rule about when those groups display, we need to set rules in the Conditional Logic section in their Advanced Settings tab.

Just choose the key as the ID of the Switch field, and the value as 0 or 1. These values correspond to No and Yes options of this field.

Set the conditional rule for Simple Product.
Set the conditional rule for Simple Product

0 is set for the Simple Product group field. So, when the Switch field is set to be No, this group will be displayed.

Set the conditional rule for Variations of Product.
Set the conditional rule for Variations of Product

Do likewise, 1 is set to the Variations of Product group field.

One more thing, there is usually more than one variation. Thus, we set the Variations of Product group as cloneable to have more spaces to add variations.

Set the Variations of Product group as cloneable to have more spaces to add variations.

After having all the custom fields, go to the Settings tab of the field group, and choose the Location as the post type of the products that we’ve just created to apply the custom fields to it.

Choose the Location as Post Type of the product.

Back to the post editor, you will see all of the created custom fields.

The created custom fields are displayed in post editor.

Now, just enter the information into the fields.

Step 3: Display the Product Variations Information on the Product Page

To display the product variations information on the product page, you normally have to go to the theme’s files to add code or use a page builder. But, in Gutenberg, you have another way with Meta Box. It has the MB Views extension to create templates without touching the theme’s files.

So, let’s create a new template using it.

Instead of typing code into the box in the Template tab, you can insert fields to get their data.

Insert fields to get data in the Template tab..

Just click the Insert Field button and choose which one you want.

click the Insert Field button and choose which one you want.

It is necessary to edit the code a little bit when we insert fields. Here is mine after the modification.

{% set product_types = post.does_this_product_have_variations %}
{% if (product_types == 0) %}
    {% for item in post.simple_product.product_images %}
        <img src="{{ item.large.url }}" width="{{ item.large.width }}" height="{{ item.large.height }}" alt="{{ item.large.alt }}">
    {% endfor %}
    {% for item in post.simple_product.product_images %}
        <img src="{{ item.thumbnail.url }}" width="{{ item.thumbnail.width }}" height="{{ item.thumbnail.height }}" alt="{{ item.thumbnail.alt }}">
    {% endfor %}
    {{ post.title }}
    {{ post.content }}
    {% if post.simple_product.promotional_price|trim is empty %}
        {{ post.simple_product.original_price }}
    {% else %}
        {{ post.simple_product.promotional_price }}
        {{ post.simple_product.original_price }}
    {% endif %}
    {% for item in post.simple_product.size %}
        {{ item.label }}
    {% endfor %}
    {{ post.simple_product.status.label }}
{% else %}
    {% for clone in post.variations_of_product %}
        {% for item in clone.product_images %}
            <img src="{{ item.large.url }}" width="{{ item.large.width }}" height="{{ item.large.height }}" alt="{{ item.large.alt }}">
        {% endfor %}
        {% for item in clone.product_images %}
            <img src="{{ item.thumbnail.url }}" width="{{ item.thumbnail.width }}" height="{{ item.thumbnail.height }}" alt="{{ item.thumbnail.alt }}">
        {% endfor %}
    {% endfor %}
    {{ post.title }}
    {{ post.content }}
    {% for clone in post.variations_of_product %}
        {{ clone.color_name.label }}
    {% endfor %}
    {% for clone in post.variations_of_product %}
        {% if clone.promotional_price|trim is empty %}
            {{ clone.original_price }}
        {% else %}
            {{ clone.promotional_price }}
            {{ clone.original_price }}
        {% endif %}
    {% endfor %}
    {% for clone in post.variations_of_product %}
        {% for item in clone.size %}
            {{ item.label }}
        {% endfor %}
    {% endfor %}
    {% for clone in post.variations_of_product %}
        {{ post.simple_product.status.label }}
    {% endfor %}
{% endif %}

In there, product_types is the variable to admit the value of the Switch field. If it is 0, it means that the product has no variation. So, the next lines of code will get the value of the fields inside the Simple Product group. Otherwise, when the returned value is 1, the value of fields inside the Variations of Product group will be displayed.

The product_types variable admits the value of the Switch field.

Also in the code, I get the value from each Product Image field twice. One displays in the large size, and one in the thumbnail size. All of them will be used to set a slider.

Get the value from each Product Image field twice to display both large size and thumbnail size.

These lines of code are to know when the product or variation has any promotion price and set a rule to display both of the original and promotional prices or just the original one.

Get the value of price field and set a rule to display it.

Next, move to the Settings section of the view. Assign this template to the single product page. And now, go to any single product page, see the result.

The product images have already turned into a slider.

It is so messy now. So, we’ll need some JS and CSS to make it more beautiful with a better layout.

Before styling, we need to edit this template a little bit more. Back to the view, then add some div tags to divide elements into sections. I put the code on our Github, you can refer to it for more clarity.

There is a notice that I added an A tag in the place where I output the color of variations. I also created a dynamic class there. It will generate different classes using the color name.

Add an A tag in the place where I output the color of variations.

I also added an attribute named data-id for price, size, status as well as the image gallery. This attribute will admit the value of the corresponding color name.

Add an attribute named data-id to admit the value of the corresponding color name for price, size, status, image gallery.

Back to the single product page, all the elements have been just reordered.

The product images have already turned into a slider.

Let’s move to the next step.

Step 4: Set Rules to Display the Variations’ Information

As you see at the beginning of this video, the images of the product variations are in a slider and the information of each variation displays only when you choose the matching color. To have it, I use some JS and CSS. However, I’m using My Custom Functionality plugin instead of adding them directly to the theme. So, when I change the theme, it won’t be affected. You can download this plugin from GitHub and install it on your website.

Download the JS and CSS Library

For the JS and CSS, I use the Slick library. It’s also available on Github. It includes several files as you can see here. But, we just need three of them.

JS and CSS files in the Slick library.

Go to the folder of the My Custom Functionality plugin. Upload them into the corresponding JS and CSS folders.

Create Custom JS for Slider and Rules

Next, to set a rule that stipulates for displaying the information of each variation as well as the slider, I’ll create a custom.js file in the js folder and add the following code to it.

Add code to custom.js file.

jQuery(document).ready(function ($) {
    $('.slider-single').slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        arrows: false,
        adaptiveHeight: false,
        infinite: false,
        useTransform: true,
        speed: 400,
        cssEase: 'cubic-bezier(0.77, 0, 0.18, 1)',

    });

    $('.slider-nav')
        .on('init', function (event, slick) {
            $('.slider-nav .slick-slide.slick-current').addClass('is-active');
        })
        .slick({
            slidesToShow: 4,
            slidesToScroll: 4,
            dots: false,
            focusOnSelect: false,
            infinite: false,
            responsive: [{
                breakpoint: 1024,
                settings: {
                    slidesToShow: 5,
                    slidesToScroll: 5,
                }
            }, {
                breakpoint: 640,
                settings: {
                    slidesToShow: 4,
                    slidesToScroll: 4,
                }
            }, {
                breakpoint: 420,
                settings: {
                    slidesToShow: 3,
                    slidesToScroll: 3,
                }
            }]
        });

    $('.slider-single').on('afterChange', function (event, slick, currentSlide) {
        $('.slider-nav').slick('slickGoTo', currentSlide);
        var currrentNavSlideElem = '.slider-nav .slick-slide[data-slick-index="' + currentSlide + '"]';
        $('.slider-nav .slick-slide.is-active').removeClass('is-active');
        $(currrentNavSlideElem).addClass('is-active');
    });

    $('.slider-nav').on('click', '.slick-slide', function (event) {
        event.preventDefault();
        var goToSingleSlide = $(this).data('slick-index');

        $('.slider-single').slick('slickGoTo', goToSingleSlide);
    });
    jQuery(".grouped-product .color-contain-group .color-group .color-name a").click(function (e) {
        jQuery(".color-contain-group .color-group .color-name").removeClass("active");
        jQuery(this).show();
        jQuery(this).parent().addClass("active");
        jQuery("div[data-id]").removeClass("active");
        jQuery("div[data-id='" + jQuery(this).attr("href").replace("#", "") + "']").addClass("active");
        jQuery('.slider-single').slick('refresh');
        jQuery('.slider-nav').slick('refresh');
        e.preventDefault();
    });

    jQuery(".size-contain-group .size-group .info .list-size a").click(function (e) {
        e.preventDefault();
    });

    jQuery('.size-contain-group .size-group .info .list-size .size-name').click(function(){
        jQuery(this).addClass('active');
        jQuery('.size-contain-group .size-group .info .list-size .size-name').not(this).removeClass('active')
    })
})

Explanation:

  • $('.slider-single').slick({ }): to create a slider for the elements that have the .slider-single class. They are product images that I set to display in a large size.
  • $('.slider-nav'): to create a slider as well. The elements which have the .slider-nav class are product images which I set to display in the thumbnail size.
  • .on('init', function (event, slick) { }): to identify which thumbnail is in the current slide. And, that thumbnail will be added a class as “is active”.
  • $('.slider-single').on('afterChange', function (event, slick, currentSlide) { }): to trigger the event that someone clicks on the large image to move to the other one, then the thumbnail slider will be changed to the corresponding thumbnail.
  • $('.slider-nav').on('click', '.slick-slide', function (event) { }): to trigger that event when someone clicks on the thumbnail slider. Then, it also displays the corresponding large image in the large slider.
  • jQuery(".grouped-product .color-contain-group .color-group .color-name a").click(function (e) { }): to trigger when someone clicks on a product color using the A tag we added in the view.
  • jQuery(".color-contain-group .color-group .color-name").removeClass("active"); jQuery(this).show(); jQuery(this).parent().addClass("active"): to remove the active class from the unselected color and add it to the selected one.
  • jQuery("div[data-id]").removeClass("active"); jQuery("div[data-id='" + jQuery(this).attr("href").replace("#", "") + "']").addClass("active"): to remove and add the active class to all the elements that have the value of the data-id attribute as the name of the color. It means that when you click on a color, all the corresponding information of that variation such as price, size, status, and image gallery will be displayed.
  • jQuery('.slider-single').slick('refresh') and jQuery('.slider-nav').slick('refresh'): to refresh both sliders to load new images.

Declare the JS and CSS Files

Now, add code inside the function custom_enqueue_files() in the plugin.php file.

wp_enqueue_style('slick', plugin_dir_url( __FILE__ ).'/assets/css/slick.css');
wp_enqueue_style('slick-theme', plugin_dir_url( __FILE__ ).'/assets/css/slick-theme.css');

wp_enqueue_script('custom', plugin_dir_url( __FILE__ ).'/assets/js/custom.js', ['jquery']);
wp_enqueue_script('slick-min', plugin_dir_url( __FILE__ ).'/assets/js/slick.min.js', ['jquery']);
wp_enqueue_script('script', plugin_dir_url( __FILE__ ).'/assets/js/script.js', ['jquery']);

Now, the product images have already turned into a slider but we cannot see all the information of each variation in the right place.

The product images have already turned into a slider.

Step 5: Style the Product Page

Traditionally, you have to add CSS to the Customizer or the theme’s file. But, with MB Views, you have a CSS tab for it.

Add code to CSS tab.

There are many classes I used in this code. You can refer to all of it on Github.

Now, back to a single product page, it turned into a new look. When you choose a color, the photo gallery will automatically change according to that color. At the same time, the sizes and prices also change correspondingly.

The product variations turned into a new look.

Last Words

As you see, displaying the product variations on the single product page with Meta Box and custom field is not something difficult. If you use another page builder, keep track of our blogs for more upcoming tutorials. If you are confused or have any ideas, let us know by leaving a comment. See you next blog!

Other case studies you might be interested in

  1. Create A Dynamic Landing Page in WordPress Using Custom Field
  2. Create a Filter to Find Hotels by Location
  3. Create an OTA Website Like Booking.com with Meta Box Plugin - P1: Create a Page to Introduce Hotel Rooms
  4. Create an OTA Website Like Booking.com with Meta Box Plugin - P2: Create Filters on the Archive Page
  5. Create an OTA Website Like Booking.com with Meta Box Plugin - P3: Create Filters for Single Hotel Pages
  6. Create Dynamic Favicon in WordPress using Meta Box plugin
  7. Create Posts Series in WordPress Using Meta Box
  8. Display The Latest Products Section - P2 - Using Meta Box and Elementor
  9. Display The Latest Products Section - P3 - Using Meta Box And Oxygen
  10. How to Add Custom Fields for WooCommerce - P2 - Using MB Views
  11. How to Add Custom Fields to Display Banners using Meta Box Plugin
  12. How to Add Guest Authors and Guest Posts - Using Meta Box
  13. How to Add Related Posts - Using Custom Fields
  14. How to Build a Hotel Booking Website Using Meta Box - P1
  15. How to Build a Hotel Booking Website Using Meta Box - P2 - Booking Page in Backend
  16. How to Build a Hotel Booking Website Using Meta Box - P4 - Booking Management Page
  17. How to Build a Hotel Booking Website Using Meta Box – P3 – Booking Page for Customer
  18. How to Create a Classified Ads Website using Meta Box
  19. How to create a FAQs page - P5 - Using Meta Box and Breakdance
  20. How to Create a Product Page - P2 - Using Meta Box and Oxygen
  21. How to Create a Product Page - P3 - Using Meta Box and Bricks
  22. How to Create a Product Page - P4 - Using Meta Box and Elementor
  23. How to Create a Product Page - P5 - Using Meta Box and Gutenberg
  24. How to Create a Product Page - P6 -Using Meta Box and Breakdance
  25. How to Create a Product Page - P7 - Using Meta Box + Kadence
  26. How to Create a Product Page - P8 - Using Meta Box and Brizy
  27. How to Create a Product Page - P9 - Using Meta Box and Divi
  28. How to Create a Product Page using Meta Box Plugin
  29. How to Create a Recipe - P2 - Using Meta Box and Oxygen
  30. How to Create a Recipe - P3 - Using Meta Box and Elementor
  31. How to Create a Recipe - P4 - Using Meta Box and Bricks
  32. How to Create a Recipe - P5 - Using Meta Box and Zion
  33. How to Create a Recipe - P6 - Using Meta Box and Brizy
  34. How to Create a Recipe - P7 - Using Meta Box and Breakdance
  35. How to Create a Recipe - P8 - Using Meta Box and Kadence
  36. How to Create a Recipe - P9 - Using Meta Box and Divi
  37. How to Create a Recipe with Meta Box Plugin
  38. How to Create a Simple Listing - P2 - Using Meta Box and Bricks
  39. How to Create a Simple Listing - P3 - Using Meta Box and Breakdance
  40. How to Create a Simple Listing - P4 - Using Meta Box and Elementor
  41. How to Create a Team Members Page - P1- Using Meta Box and Elementor
  42. How to Create a Team Members Page - P2 - Using Meta Box and Oxygen
  43. How to Create a Team Members Page - P3 - Using Meta Box and Bricks
  44. How to Create a Team Members Page - P4 - Just Meta Box
  45. How to Create a Team Members Page - P6 - using Meta Box and Breakdance
  46. How to Create a Team Members Page - P7 - Using Meta Box and Kadence
  47. How to Create a Video Gallery Page - P2 - Using Meta Box + Bricks
  48. How to Create a Video Gallery Page - P3 - Using Meta Box and Breakdance
  49. How to Create a Video Gallery Page - P4 - Using Meta Box + Elementor
  50. How to Create a Video Gallery Page - P5 - Using MB Views
  51. How to Create a Video Gallery Page - P6 - Using Meta Box and Zion
  52. How to Create a Video Gallery Page Using Meta Box + Oxygen
  53. How to Create ACF Flexible Content Field with Meta Box
  54. How to Create an Auto-Updated Cheat Sheet in WordPress
  55. How to Create an FAQs Page - P1 - Using Meta Box and Elementor
  56. How to create an FAQs page - P2 - Using Meta Box and Oxygen
  57. How to create an FAQs page - P4 - Using Meta Box and Bricks
  58. How to Create an FAQs Page - P6 - Using MB Views
  59. How to Create an FAQs Page - P7 - Using Meta Box and Divi
  60. How to Create an FAQs Page - P8 - Using Meta Box and Kadence
  61. How to Create an FAQs Page -P3- Using Meta Box
  62. How to Create Buttons with Dynamic Link using Custom Fields
  63. How to Create Category Thumbnails & Featured Images Using Custom Fields
  64. How to Create Download and Preview Buttons - P1 - Using Meta Box and Bricks
  65. How to Create Download and Preview Buttons - P2 - Using Meta Box and Oxygen
  66. How to Create Download and Preview Buttons - P3 - Using MB Views
  67. How to Create Download Buttons in WordPress - Using Custom Fields
  68. How to Create Dynamic Landing Page in WordPress - P1 - Using Meta Box and Elementor
  69. How to Create Dynamic Landing Page in WordPress - P2 - Using Meta Box and Bricks
  70. How to Create Menus for Restaurants - P1 - Using Meta Box and Elementor
  71. How to Create Menus for Restaurants - P2- Using Meta Box and Bricks
  72. How to Create Notification Using Custom HTML Field
  73. How to Create Online Admission Form for School or University
  74. How to Create Online Reservation Form for Restaurants using Meta Box
  75. How to Create Relationships - P1 - Using Meta Box and Oxygen
  76. How to Create Relationships - P2 - Using Meta Box and Bricks
  77. How to Create Relationships - P3 - Using MB Views
  78. How to Create Relationships - P4 - Using Meta Box and Breakdance
  79. How to Create Taxonomy Thumbnails & Featured Images - P2 - Using Meta Box and Oxygen
  80. How to Create Taxonomy Thumbnails & Featured Images - P3 - Using Meta Box and Bricks
  81. How to Create Taxonomy Thumbnails & Featured Images - P4 - Using MB Views
  82. How to Create YouTube Video Timestamps on WordPress Website - P1 - Using MB Views
  83. How To Display All Listings On A Map With Meta Box
  84. How to Display Author Bio in WordPress - P1 - Using Meta Box and Bricks
  85. How to Display Images from Cloneable Fields - P1 - with Gutenberg
  86. How to Display Images from Cloneable Fields - P2 - Using Meta Box and Oxygen
  87. How to Display Images from Cloneable Fields - P3 - with Elementor
  88. How to Display Images from Cloneable Fields - P4 - with Bricks
  89. How to Display Opening Hours for Restaurants - P1 - Using Meta Box + Gutenberg
  90. How to Display Opening Hours for Restaurants - P2 - Using Meta Box and Oxygen
  91. How to Display Product Variations - P1 - Using Meta Box and Gutenberg
  92. How to Display Product Variations - P2 - Using Meta Box and Oxygen
  93. How to Display Product Variations - P3 - Using Meta Box and Bricks
  94. How to Display the Dynamic Banners - P2 - Using Meta Box and Bricks
  95. How to Display The Latest Products - P5 - Using Meta Box and Bricks
  96. How to Display the Latest Products - P6 - using Meta Box and Breakdance
  97. How to Display the Latest Products - P7 - Using Meta Box + Kadence
  98. How to Display the Latest Products Section - P4 - Using Meta Box + Zion
  99. How to Display the Most Viewed Posts - P1 - using MB Views

Leave a Reply

Your email address will not be published. Required fields are marked *