【问题标题】:Product price suffix with a price calculation based on weight in WooCommerce在 WooCommerce 中基于重量计算价格的产品价格后缀
【发布时间】:2021-03-26 08:57:07
【问题描述】:

我正在使用 “https://stackoverflow.com/questions/53435276/custom-product-price-suffix-on-based-on-product-categories-in-woocommerce/53438506#53438506” em> 允许以这种方式调整我的定价显示的答案线程:

    $price .= ' ' . __('/ $7.50 per serving');

但我真正想要的是让$price 输出商品的价格除以商品的重量。我该怎么做?

这是我的实际代码稍作改动(使用has_product_categories()from this thread

add_filter( 'woocommerce_get_price_html', 'conditional_price_suffix', 10, 2 );
function conditional_price_suffix( $price, $product ) {
    // Handling product variations
    $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

    // HERE define your product categories (can be IDs, slugs or names)
    $product_categories = array('monthly-menus');

    if( has_product_categories( $product_categories, $product_id ) )
        $price .= ' ' . __('/ $7.50 per serving');

    return $price;
}

我尝试了一大堆在前端输出NAN 的东西。不要以为我做对了!

【问题讨论】:

    标签: php wordpress woocommerce product price


    【解决方案1】:

    以下将添加您的前缀以及每份的计算价格:

    add_filter( 'woocommerce_get_price_html', 'conditional_price_suffix', 10, 2 );
    function conditional_price_suffix( $price, $product ) {
        $weight    = (float) $product->get_weight();
        $raw_price = (float) wc_get_price_to_display($product);
    
        // Handling product variations
        $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();
    
        // HERE define your product categories (can be IDs, slugs or names)
        $product_categories = array('monthly-menus');
        $product_categories = array('clothing');
    
        if( has_product_categories( $product_categories, $product_id ) && $weight > 0 )
            $price .= ' ' . sprintf( __('/ %s per serving'), strip_tags( wc_price( $weight / $raw_price ) ) );
        return $price;
    }
    

    您必须包含has_product_categories() 来自this thread 的功能代码。

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且有效。

    【讨论】:

      猜你喜欢
      • 2021-05-19
      • 2019-02-02
      • 2019-02-12
      • 2019-12-25
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      相关资源
      最近更新 更多