且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Woocommerce 3上显示默认变动价格和节省金额

更新时间:2023-11-30 12:20:22

尝试以下操作,我们首先在其中搜索可变产品(默认变动价格).

Try the following, where we search first for variable products, the default variation prices.

add_filter( 'woocommerce_get_price_html', 'custom_price_format', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'custom_price_format', 10, 2 );
function custom_price_format( $price, $product ) {

    // 1. Variable products
    if( $product->is_type('variable') ){

        // Searching for the default variation
        $default_attributes = $product->get_default_attributes();
        // Loop through available variations
        foreach($product->get_available_variations() as $variation){
            $found = true; // Initializing
            // Loop through variation attributes
            foreach( $variation['attributes'] as $key => $value ){
                $taxonomy = str_replace( 'attribute_', '', $key );
                // Searching for a matching variation as default
                if( isset($default_attributes[$taxonomy]) && $default_attributes[$taxonomy] != $value ){
                    $found = false;
                    break;
                }
            }
            // When it's found we set it and we stop the main loop
            if( $found ) {
                $default_variaton = $variation;
                break;
            } // If not we continue
            else {
                continue;
            }
        }
        // Get the default variation prices or if not set the variable product min prices
        $regular_price = isset($default_variaton) ? $default_variaton['display_price']: $product->get_variation_regular_price( 'min', true );
        $sale_price = isset($default_variaton) ? $default_variaton['display_regular_price']: $product->get_variation_sale_price( 'min', true );
    }
    // 2. Other products types
    else {
        $regular_price = $product->get_regular_price();
        $sale_price    = $product->get_sale_price();
    }

    // Formatting the price
    if ( $regular_price !== $sale_price && $product->is_on_sale()) {
        // Percentage calculation and text
        $percentage = round( ( $regular_price - $sale_price ) / $regular_price * 100 ).'%';
        $percentage_txt = __(' Save', 'woocommerce' ).' '.$percentage;

        $price = '<del>' . wc_price($regular_price) . '</del> <ins>' . wc_price($sale_price) . $percentage_txt . '</ins>';
    }
    return $price;
}

代码进入您的活动子主题(或活动主题)的function.php文件中.经过测试,可以正常工作.

Code goes in function.php file of your active child theme (or active theme). Tested and works.

现在,此代码将永远无法获得所选的变化价格,因为它是客户端浏览器上的实时事件,处理起来要复杂得多(在这种情况下,将需要Php和Jquery).

Now this code will never get the selected variation price as it's a live event on client browser that is much more complicated to handle (Php and Jquery will be needed in this case).

相关的链接的答案:显示最低的变化WooCommerce中的价格和折扣百分比