Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce How do I get price next each variation

I'm using the latest WC and I really want prices to show next to each variation, for a better overview.

I have trouble finding the proper code for my functions.php to display prices next to each variation. I saw several older posts and noone of them really worked.

I tried the following:

add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );

function display_price_in_variation_option_name( $term ) {
    global $wpdb, $product;

    if ( empty( $term ) ) return $term;
    if ( empty( $product->id ) ) return $term;

    $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 . ' (' . wp_kses( woocommerce_price( $_product->get_price() ), array() ) . ')';
    }
    return $term;

}

This one didn't work. I couldn't see any changes after implementing one way or the other. But its for older versions of WC, although Im beginning to believe that my theme is blocking it somehow. Im using Shopera.

like image 521
BB admn Avatar asked Nov 20 '22 08:11

BB admn


1 Answers

Since there is no id argument woocommerce_variation_option_name, we could do this with script.

add_action( "wp_head", "function_to_woo_script" );

function function_to_woo_script () {
    ?>
    <script>
    $ = jQuery;
    $(document).ready(function(){
        var json_product    =   jQuery.parseJSON( $(".variations_form").attr("data-product_variations") );
        var currency    =   "$";
        for( i = 0; i < json_product.length; i++ ) {
            var attr_name   =   $(".variations select").attr("data-attribute_name");
            $(".variations select option[value='"+json_product[i].attributes[attr_name]+"']").html( json_product[i].attributes[attr_name] + " - " + currency + json_product[i].display_regular_price );
        }
    });
    </script>
    <?php 
}

Result

like image 97
hemnath mouli Avatar answered Nov 22 '22 00:11

hemnath mouli