Reputation: 197
I have two attributes in my woocommerce single product page that I have added, "Metal" and "Ring Size". They are "variations" such that they are drop down selections on my product page.
I want to be able to on click of my button, I can be able to grab the selected value and put it onto my URL parameter.
I solved everything up to the part where the value that is grabbed isn't correct.
I have so far tried this but it is just giving me a list of this attributes possible values/selections and not the single selected value..
$metal = $product->get_attribute( 'Metal' );
http://example.com/?metal=18K%20White%20Gold%20|%2018K%20Yellow%20Gold%20|%20Rose%20Gold%20|%20Platinum
I just want what I selected on the drop down, something like this:
http://example.com/?metal=Platinum
Upvotes: 2
Views: 4725
Reputation: 253784
Here is an example of code that may be you will need to customize a little bit. This code will:
home-url/?metal=
… (home-url
is your website url)Here is the code:
add_filter( 'woocommerce_single_variation', 'get_variation_selectected_value', 25 );
function get_variation_selectected_value() {
global $product;
// Display button (Just for testing purpose)
// You can remove or comment the line of code below …
// But you need to set your url like: http://example.com/?metal=
echo '<br /><a href="'.home_url("/?metal=").'" class="book-now button">'. __('Make an Appointment Now') .'</a>';
// The script
?>
<script>
jQuery(document).ready(function($) {
// Get the default value
var selectedValue = $('select#metal option:checked').val(),
hrefAttribute = $('a.book-now').attr("href");
$('a.book-now').attr("href", hrefAttribute+selectedValue);
// Display on browser console (for test)
console.log($('a.book-now').attr("href"));
// Get the live selected value
$('select#metal').blur( function(){
selectedValue = $('select#metal option:checked').val();
hrefAttribute = $('a.book-now').attr("href");
$('a.book-now').attr("href", hrefAttribute+selectedValue);
// Display on browser console (for test)
console.log($('a.book-now').attr("href"));
});
});
</script>
<?php
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
The code has been tested (with another attribute) and just works.
Upvotes: 1