This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

[Webinar] Register Now to Learn Component Based Web Development With Builderius. Click here to register

How to Customize Product Variations in WooCommerce

Updated on December 12, 2022

3 Min Read
WooCommerce Product variations

If you are a WooCommerce store owner and want to sell something with different designs. For example, a t-shirt with 5 different sizes and 4 colors; for a total of 20 different variations of the same product. Each variation can have different prices, SKU numbers, images, and videos, and certainly also have a different warehouse.

WooCommerce offers adding product variations by default, but you can customize them. In this article, I’ll explain how you can customize product variations in WooCommerce using different attributes.

If you are interested in exploring WooCommerce product variation and related settings, there is no better place to start than the official WooCommerce Product Variation documentation. Besides, WooCommerce makes it possible to generate variable products (complete with attributes) through code. Let’s see them in the next section!

From launching to customizing your WooCommerce stores, Cloudways is at your service.

Whether you’re a beginner or an expert, Cloudways Platform is based on UI, where you can create and customize your online store in a few seconds.

Create WooCommerce Variable Products with Attributes

The following code snippet defines variable product ID through a custom function that actually adds or creates a product variation. Note that the parent product for the variable product is required for setting the attributes, such as the array of attribute/value, SKU, prices, and stock.

As you can see, this data has to be stored in a formatted multidimensional array. This function will check if the values of the attribute already exist. If not, it creates an entry for a product attribute and then sets it in the parent variable product.

function create_product_variation( $product_id, $variation_data ){
$product = wc_get_product($product_id);
$variation_post = array(
        'post_title'  => $product->get_title(),
        'post_name'   => 'product-'.$product_id.'-variation',
     'post_status' => 'publish',
     'post_parent' => $product_id,
        'post_type'   => 'product_variation',
     'guid'    => $product->get_permalink()
);
$variation_id = wp_insert_post( $variation_post );
$variation = new WC_Product_Variation( $variation_id );
foreach ($variation_data['attributes'] as $attribute => $term_name )
{
     $taxonomy = 'pa_'.$attribute; 
     if( ! taxonomy_exists( $taxonomy ) ){
            register_taxonomy(
                $taxonomy,
                'product_variation',
                array(
                    'hierarchical' => false,
                    'label' => ucfirst( $attribute ),
                    'query_var' => true,
                    'rewrite' => array( 'slug' => sanitize_title($attribute) ), 
             )
         );
     }
     if( ! term_exists( $term_name, $taxonomy ) )
            wp_insert_term( $term_name, $taxonomy ); 
     $term_slug = get_term_by('name', $term_name, $taxonomy )->slug; 
        $post_term_names =  wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') );
     if( ! in_array( $term_name, $post_term_names ) )
            wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
        update_post_meta( $variation_id, 'attribute_'.$taxonomy, $term_slug );
}
if( ! empty( $variation_data['sku'] ) )
        $variation->set_sku( $variation_data['sku'] );
if( empty( $variation_data['sale_price'] ) ){
        $variation->set_price( $variation_data['regular_price'] );
} else {
        $variation->set_price( $variation_data['sale_price'] );
        $variation->set_sale_price( $variation_data['sale_price'] );
}
    $variation->set_regular_price( $variation_data['regular_price'] );
if( ! empty($variation_data['stock_qty']) ){
        $variation->set_stock_quantity( $variation_data['stock_qty'] );
        $variation->set_manage_stock(true);
        $variation->set_stock_status('');
} else {
        $variation->set_manage_stock(false);
}
    $variation->set_weight(''); 
    $variation->save(); 
}

WooCommerce Variable Products and Their Outputs

Remember that all the code snippets go to the functions.php file. I will now define the major statements and functions in the code snippets:

  • wc_get_product($product_id) Gets the variable product object.
  • wp_insert_post( $variation_post ) Creates the product variation.
  • WC_Product_Variation( $variation_id )  Gets an instance of the WC_Product_Variation object.
  • register_taxonomy  If taxonomy doesn’t exist, this will create it.
  • wp_insert_term in the IF condition, check if the term name exists. If not, create it.
  • $post_term_names Gets the post Terms names from the parent variable product.
  • wp_set_post_terms in IF condition checks if the post-term exists and, if not, set it in the parent variable product.
  • update_post_meta saves the attribute data in the product variation
  • $variation->set_sku sets/saves all other data in SKU
  • $variation_data[‘sale_price’] contains prices values in product variations
  • $variation_data[‘stock_qty’] contains stock values in product variations
  • $variation->save() saves attribute values of product variations

Summary

As you can see, creating a WooCommerce variable product through code offers a lot of flexibility that developers can leverage for their clients. Remember to place the code in the functions.php file.

If you want to check out this code on a staging environment, just sign up for WooCommerce hosting and try 3 days for free. If you need to clarify a point or suggest an improvement, please leave a comment below.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Great performance for the price, and plenty of control”

Sean P [SMB Owner]

Owais Alam

is the WordPress Community Manager at Cloudways - A Managed WooCommerce Hosting Platform and a seasoned PHP developer. He loves to develop all sorts of websites on WordPress and is in love with WooCommerce in particular. You can email him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

" "
Unleash The Cloud.
Not Budgets.

For 4 Months +
Up To 30 Free Migrations

Cyber Week

SAVINGS
Time Left In Offer
  • 0

    Days

  • 0

    Hours

  • 0

    Minutes

  • 0

    Seconds

40% OFF

On All Plans

GET THE DEAL NOW