Home » WooCommerce: Get Currently Selected Variation ID

WooCommerce: Get Currently Selected Variation ID

by Tutor Aspire

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):

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 tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 5
 * @donate $9     https://tutoraspire.com

add_action( 'woocommerce_before_add_to_cart_quantity', 'tutoraspire_display_dropdown_variation_add_cart' );

function tutoraspire_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);
" );

You may also like