By default, WooCommerce plugin will display product variations as a drop down menu in the single product page. For example, a T-shirt would be available in various sizes/variations (say M, L, XL etc…) and those options will be displayed via select drop down list…Upon selection, the product’s price will change accordingly (you might have set different price for different size/variation) and as I told already, WooCommerce has this feature by default. But my client had other idea – he asked me to display product variation price inside the variation select drop down menu, so when the drop down list is clicked, the menu would display variations along with its price in the brackets next to it (like the one shown in the below image).
So how can you do that?
Fortunately, I found a hack posted on stackoverflow.com by ratnakar-store-apps. All you need to do is to copy the below code and paste it in functions.php file.
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );
function display_price_in_variation_option_name( $term ) {
global $wpdb, $product;
$result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE name = '$term'" );
$term_slug = ( !empty( $result ) ) ? $result[0] : $term;
$query = "SELECT postmeta.post_id AS product_id
FROM {$wpdb->prefix}postmeta AS postmeta
LEFT JOIN {$wpdb->prefix}posts AS products ON ( products.ID = postmeta.post_id )
WHERE postmeta.meta_key LIKE 'attribute_%'
AND postmeta.meta_value = '$term_slug'
AND products.post_parent = $product->id";
$variation_id = $wpdb->get_col( $query );
$parent = wp_get_post_parent_id( $variation_id[0] );
if ( $parent > 0 ) {
$_product = new WC_Product_Variation( $variation_id[0] );
return $term . ' (' . woocommerce_price( $_product->get_price() ) . ')';
}
return $term;
}
Note: It makes sense only if you have a variable product with different price set for each variation.
Perfect, Thanks.
dont forget to replace this
Replace
return $term . ‘ (‘ . woocommerce_price( $_product->get_price() ) . ‘)’;
By
return $term . ‘ (‘ . $_product->get_price() . ‘)’;
.
that broke my website because it’s then printing out the entire html around the variation title so the drop down shows up as
T1 (<span class=”woocommerce-Price-amount amount”><span class=”woocommerce-Price-currencySymbol”>$</span>2.00</span>)
Have this issue as well
Same issue
Replace
return $term . ‘ (‘ . woocommerce_price( $_product->get_price() ) . ‘)’;
By
return $term . ‘ (‘ . $_product->get_price() . ‘)’;
Yes It works.. thanks