phpwordpresswoocommerceproduct

Replace Woocommerce product variable price range from custom field values


I want to use a custom field to add price for vendors in variable products. So, I am using the following code to get the maximum and minimum price of custom field of variable product, but it return nothing. Please help me to find how can get the price from custom field for variable products.

    // Min and max variable prices
    add_filter( 'woocommerce_variable_sale_price_html', 'new_variable_price_format', 10, 2 );
    add_filter( 'woocommerce_variable_price_html', 'new_variable_price_format', 10, 2 );
    function new_variable_price_format( $price, $product ) {
    $price = get_post_meta( $product->get_id(), 'vendor_price_regu');
    echo "<pre>";
    print_r($price);
    echo "</pre>";
    return $price;
    }

Solution

  • As this is about the displayed variable price range, you need to get all variations prices and to display the min and the max custom formatted prices to make it work:

    add_filter( 'woocommerce_variable_price_html', 'custom_variable_price_html', 10, 2 );
    function custom_variable_price_html( $price, $product) {
        $prices = [];
        foreach($product->get_children() as $variation_id ){
            if( $vprice = get_post_meta( $variation_id, 'vendor_price_regu', true ) )
                $prices[] = $vprice;
        }
    
        if( sizeof($prices) > 0 ){
            sort($prices);
    
            $min_price = reset( $prices );
            $max_price = end( $prices );
    
            if ( $min_price == $max_price ) {
                 $price = wc_price($min_price);
            } else {
                $price = wc_price($min_price) . ' - ' . wc_price($max_price);
            }
        }
        return $price;
    }
    

    Code goes in function.php file of your active child theme (or active theme). It should work.