'How to get Woocommerce product variation id into a PHP variable for use with custom add to cart urls?
Using Woocommerce, I need to be able to add a variable product to the cart within a custom add to cart URL, such as with the following example, where 88 is the variation id:
https://yourdomain.com/?add-to-cart=88&quantity=1
I need the variation id to be a PHP variable. This is easy with the product id but not with the variation id. I found some Javascript code that gets the variation id and sends an alert with the id.
The following code goes inside my theme's functions.php. It successfully gets the variation id and puts it into a Javascript variable called var_id.
How do I pass this variable to PHP?
Edit: Answers to similar questions seem to be talking about the Ajax Post() method. I tried this method but it didn't seem to work for this example, although it may need a different syntax for the below code?
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);
}
});
" );
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|