WooCommerce variable products: keep only “min” price with a custom label

前端 未结 1 1923
孤街浪徒
孤街浪徒 2020-12-06 21:52

In the functions file I have added a filter hook to add a custom label before the variation product \"min\" price.

How can I get the label in the same line as the p

相关标签:
1条回答
  • 2020-12-06 22:35

    Since WooCommerce 3, woocommerce_variable_sale_price_html hook is deprecated and not anymore useful. If you don't care about "min" sale price (when the min price is on sale), you can use this:

    add_filter( 'woocommerce_variable_price_html', 'custom_min_max_variable_price_html', 10, 2 );
    function custom_min_max_variable_price_html( $price, $product ) {
        $prices = $product->get_variation_prices( true );
        $min_price = current( $prices['price'] );
    
        $min_price_html = wc_price( $min_price ) . $product->get_price_suffix();
        $price = sprintf( __( 'From %1$s', 'woocommerce' ), $min_price_html );
    
        return $price;
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    Tested and works on WooCommerce 3+. You will get something like this:

    If you care about "min" sale price (when the min price is on sale), and you want to display both prices, you should use this code instead:

    add_filter( 'woocommerce_variable_price_html', 'custom_min_max_variable_price_html', 10, 2 );
    function custom_min_max_variable_price_html( $price, $product ) {
        $prices = $product->get_variation_prices( true );
        $min_price = current( $prices['price'] );
    
        $min_keys = current(array_keys( $prices['price'] ));
        $min_price_regular = $prices['regular_price'][$min_keys];
        $min_price_html = wc_price( $min_price ) . $product->get_price_suffix();
    
        if( $min_price_regular != $min_price ){ // When min price is on sale (Can be removed)
            $min_price_regular_html = '<del>' . wc_price( $min_price_regular ) . $product->get_price_suffix() . '</del>';
            $min_price_html = $min_price_regular_html .'<ins>' . $min_price_html . '</ins>';
        }
        $price = sprintf( __( 'From %1$s', 'woocommerce' ), $min_price_html );
    
        return $price;
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    Tested and works on WooCommerce 3+. You will get something like this:

    To handle when all variations prices are the same:

    WooCommerce variable products: Display the min price with a custom text for different prices

    0 讨论(0)
提交回复
热议问题