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.

A new menu appears after 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.

The example of inserting a field in the Template tab.

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 a User List On the Frontend with Meta Box
  9. Display The Latest Products Section - P2 - Using Meta Box and Elementor
  10. Display The Latest Products Section - P3 - Using Meta Box And Oxygen
  11. How to Add Custom Fields to Display Banners using Meta Box Plugin
  12. How to Add Guest Author in WordPress using Meta Box (Part 1)
  13. How to Add Guest Author in WordPress using Meta Box (Part 2)
  14. How to Add Related Posts to WordPress Using Meta Box
  15. How to Build a Hotel Booking Website Using Meta Box - P1
  16. How to Build a Hotel Booking Website Using Meta Box - P2 - Booking Page in Backend
  17. How to Build a Hotel Booking Website Using Meta Box - P4 - Booking Management Page
  18. How to Build a Hotel Booking Website Using Meta Box – P3 – Booking Page for Customer
  19. How to Create a Classified Ads Website using Meta Box
  20. How to Create a Product Page using Meta Box Plugin
  21. How to Create a Recipe with Meta Box Plugin
  22. How to Create ACF Flexible Content Field with Meta Box
  23. How to Create an Auto-Updated Cheat Sheet in WordPress
  24. How to Create an FAQs Page Using Meta Box
  25. How to Create Buttons with Dynamic Link using Custom Fields
  26. How to Create Category Thumbnails & Featured Images Using Custom Fields
  27. How to Create Download Buttons Using Custom Fields with Meta Box Plugin
  28. How to Create Online Admission Form for School or University
  29. How to Create Online Reservation Form for Restaurants using Meta Box
  30. How to Create Taxonomy Thumbnails & Featured Images - P2 - Using Meta Box and Oxygen
  31. How to Display Images from Cloneable Fields - P1 - with Gutenberg
  32. How to Display Images from Cloneable Fields - P2 - with Oxygen
  33. How to Display Opening Hours for Restaurants - P1 - Using Meta Box + Gutenberg
  34. How to Display Product Variations - P1 - Using Meta Box and Gutenberg
  35. How to Display Product Variations - P2 - Using Meta Box and Oxygen
  36. How to Manually Reorder Posts with Meta Box
  37. How to Use Custom HTML Field to Output Beautiful Texts or Output Custom CSS

Leave a Reply

Your email address will not be published.