WooCommerce: Get Currently Selected Variation ID

We’ve seen a lot of PHP so far on Business Bloomer – WooCommerce after all is a bunch of PHP files! However, sometimes PHP is just not enough, mostly when you need to work with variable products and the “currently selected variation”.

In fact, WooCommerce uses jQuery (a JavaScript Library) to handle variations on the frontend and show conditional content (variation price, description, add to cart) based on the dropdown selection. So, to detect the current variation ID we must use jQuery as well. Here’s how!

WooCommerce: Detect Selected Variation ID

PHP/jQuery Snippet: Get Currently Selected Variation ID @ WooCommerce Single Product Page

I won’t go into too much detail, but in order to “get” the variation ID I thought of a nice workaround. When you select a variation, WooCommerce assigns the variation ID to a hidden input on the frontend (293 in this example):

<input type="hidden" name="variation_id" class="variation_id" value="293">

Therefore, there is no need to “redo” the work – let’s take advantage of this existing script and simply “read” the value of the input when the input changes ๐Ÿ™‚

In my snippet, an alert (see screenshot above) will popup when a variation is found – but of course you can do much more with this, such as loading conditional content, executing PHP, running events, and so on.

/**
 * @snippet       Get Current Variation ID @ WooCommerce Single Product
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 5
 * @community     https://businessbloomer.com/club/
 */

add_action( 'woocommerce_before_add_to_cart_quantity', 'bbloomer_display_dropdown_variation_add_cart' );

function bbloomer_display_dropdown_variation_add_cart() {
	global $product;
	if ( $product->is_type( 'variable' ) ) {
		wc_enqueue_js( "
			$( 'input.variation_id' ).change( function(){
				if( '' != $(this).val() ) {
					var var_id = $(this).val();
					alert('You just selected variation #' + var_id);
				}
			});
		" );
	}
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: Custom Add to Cart URLs – The Ultimate Guide
    In WooCommerce you can add a product to the cart via a custom link. You just need to use the “add-to-cart” URL parameter followed by the product ID. This tutorial will show you how to create custom URLs to add simple, variable and grouped products to the cart – as well as defining the add […]
  • WooCommerce Visual Hook Guide: Single Product Page
    Here’s a visual hook guide for the WooCommerce Single Product Page. This is part of my “Visual Hook Guide Series“, through which you can find WooCommerce hooks quickly and easily by seeing their actual locations (and you can copy/paste). If you like this guide and it’s helpful to you, let me know in the comments! […]
  • WooCommerce: Disable Variable Product Price Range $$$-$$$
    You may want to disable the WooCommerce variable product price range which usually looks like $100-$999 when variations have different prices (min $100 and max $999 in this case). With this snippet you will be able to hide the highest price, and add a “From: ” prefix in front of the minimum price. At the […]
  • WooCommerce: Hide Price & Add to Cart for Logged Out Users
    You may want to force users to login in order to see prices and add products to cart. That means you must hide add to cart buttons and prices on the Shop and Single Product pages when a user is logged out. All you need is pasting the following code in your functions.php (please note: […]
  • WooCommerce: Add Custom Field to Product Variations
    Adding and displaying custom fields on WooCommerce products is quite simple. For example, you can add a “RRP/MSRP” field to a product, or maybe use ACF and display its value on the single product page. Easy, yes. Unfortunately, the above only applies to “simple” products without variations (or the parent product if it’s a variable […]

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

10 thoughts on “WooCommerce: Get Currently Selected Variation ID

  1. Hi Rodolfo,
    just found this snippet and it works perfectly but, as intended, only on the single product page. How do I get the actual variation id on the loop / archive pages?

    Thanks.
    Michael

    1. There is no variation selection in the loop by default. Did you use a plugin for that?

  2. Hi ,
    Its great article, snippet working on my single product page. But how can i get this javascript var into php variable into single product page ?

    1. Hello Bhuwan, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  3. Hey there – i wonder if you have an article about how to hide certain attributes depending on the selection of another attribute on the product Page. Please let me know, searching this already since a very long time.

    1. I don’t, sorry ๐Ÿ™‚ This is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  4. Hi,

    I would like for the single product page to display the parent SKU even when a variation has been selected, while ensuring the variation’s SKU is still distinct from the parent SKU.
    As a workaround of the above I would even accept not to display any SKU when a variation is selected.
    I do have a meta.php within my theme that is echoing product meta. The condition there is given by this line:

    <?php if ( wc_product_sku_enabled() && ( $product->get_sku() || $product->is_type( 'variable' ) ) ) : ?>
    

    I am seeking for a condition that defines when a variation is selected.

    Thank you.

    1. Hello Attila – thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  5. Hi Rodolfo, this snippet works perfectly, but please, what about if I need to display the Name of selected variation? (in my case adding this after the title?)

    Tah

    1. Luca – thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

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