代码之家  ›  专栏  ›  技术社区  ›  Adrian

将折扣百分比添加到Woocommerce中的可变产品价格范围

  •  2
  • Adrian  · 技术社区  · 8 年前

    使用Woocommerce,我已使用以下代码从产品档案页面中依次删除了销售徽章和价格:

    // Remove Sales Flash
    add_filter('woocommerce_sale_flash', 'woo_custom_hide_sales_flash');
    function woo_custom_hide_sales_flash()
    {
        return false;
    }
    
    // Remove prices on archives pages
    remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
    

    所有产品都是可变产品,所有变化都有相同的价格。实际上所有的价格都是销售价格。

    我想在每个可变价格范围后添加折扣百分比, 在单个产品页面中 . 我已尝试使用以下代码:

    add_filter( 'woocommerce_sale_price_html', 'woocommerce_custom_sales_price', 10, 2 );
    function woocommerce_custom_sales_price( $price, $product ) {
        $percentage = round( ( ( $product->regular_price – $product->sale_price ) / 
        $product->regular_price ) * 100 );
        return $price . sprintf( __(' Save %s', 'woocommerce' ), $percentage . '%' );
    }
    

    但我什么都没得到

    我做错了什么,怎么做?

    在此方面的任何帮助都将不胜感激。

    1 回复  |  直到 8 年前
        1
  •  3
  •   LoicTheAztec    8 年前

    我一直在测试代码,因为您的目标是可变产品的销售价格范围,所以最好在中使用自定义挂钩函数 woocommerce_format_sale_price 位于 wc_format_sale_price() 作用

    这将允许在所有变体具有相同价格时,在价格范围后显示保存的折扣百分比。如果变更价格不同,则该百分比将仅出现在变更价格上。

    因此,我重新访问了您的代码:

    // Removing sale badge
    add_filter('woocommerce_sale_flash', '__return_false');
    
    // Removing archives prices
    remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
    
    // Add the saved discounted percentage to variable products
    add_filter('woocommerce_format_sale_price', 'add_sale_price_percentage', 20, 3 );
    function add_sale_price_percentage( $price, $regular_price, $sale_price ){
        // Strip html tags and currency (we keep only the float number)
        $regular_price = strip_tags( $regular_price );
        $regular_price = (float) preg_replace('/[^0-9.]+/', '', $regular_price);
        $sale_price = strip_tags( $sale_price );
        $sale_price = (float) preg_replace('/[^0-9.]+/', '', $sale_price);
    
        // Percentage text and calculation
        $percentage  = __('Save', 'woocommerce') . ' ';
        $percentage .= round( ( $regular_price - $sale_price ) / $regular_price * 100 );
    
        // return on sale price range with "Save " and the discounted percentage
        return $price . ' <span class="save-percent">' . $percentage . '%</span>';
    }
    

    代码进入功能。活动子主题(活动主题)的php文件。

    已测试并正常工作。