How To Insert Woocommerce Product Price After Variation Name

Today we will insert the product price after the variation name on the product detail page of variation products.

A variable product is a type of WooCommerce product with multiple prices that offers a set of variations in a single product with control over different attributes.

First, create the variable woocommerce product from the backend with some attributes.

Create the variations for available attributes.

Generally product variation dropdown only contains the variation name.

We will add the price with the variable name in the variation dropdown of the product details page.

Please insert the below code to the child theme’s function.php and check on the front end of the product detail page.

//Add prices to variations
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] );
    $itemPrice = strip_tags (woocommerce_price( $_product->get_price() ));
    //this is where you can actually customize how the price is displayed
    return $term . ' (' . $itemPrice . ')';
  return $term;

That’s it. Now your shop users can see the prices of the variations of variable products.

Please check the below video for the output.

Submit a Comment

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


Select Categories