在Woocommerce中显示商店页面上分组产品的总价

时间:2018-02-22 13:47:37

标签: php wordpress woocommerce product price

我想显示我的分组产品的总价格而不是价格范围。我已经使用此代码段在产品页面上修复了此问题。

如何在商店页面上使用此代码或修复我的问题?

global $product;
$price = $product->get_price_html();
if ( $product->get_type() == 'grouped') {
    $children = $product->get_children();
    $price = 0;
    foreach ($children as $key => $value) {
        $_product = wc_get_product( $value );
        $price += $_product->get_price();
    }
    $price = get_woocommerce_currency_symbol( '' ) . ' ' . $price;
}
?>
<p class="price"><?php echo $price; ?></p>

3 个答案:

答案 0 :(得分:0)

尝试使用全局过滤器来更改商店循环中返回的价格:

add_filter( 'woocommerce_get_price_html', 'highest_price', 10, 2 );

function highest_price( $price, $product ) {
  if ( $product->get_type() == 'grouped') {
    $children = $product->get_children();
    $price = 0;
    foreach ($children as $key => $value) {
      $_product = wc_get_product( $value );
      $price += $_product->get_price();
    }
    $price = get_woocommerce_currency_symbol( '' ) . ' ' . $price;
  }
  return $price;
}

我无法测试此解决方案,但如果它无效,请尝试将过滤器添加到其他功能,而不是woocommerce_get_price_html,例如woocommerce_template_loop_price

答案 1 :(得分:0)

亚历山大的答案使用正确的钩子并起作用。我只是以更干净的方式修改你的代码,使用例如Woocommerce格式化函数wc_price()。您必须从单个产品页面 删除自己的代码 ,因为此代码无处不在(在单个产品页面和存档页面上也是如此:

add_filter( 'woocommerce_get_price_html', 'grouped_product_price', 10, 2 );
function grouped_product_price( $price, $product ) {
    if ( $product->is_type( 'grouped' ) && ! is_admin() ) {
        $grouped_price = 0;
        foreach ($product->get_children() as $child_id ) {
            $child = wc_get_product( $child_id );
            $grouped_price += $child->get_price();
        }
        $price = wc_price($grouped_price);
    }
    return $price;
}

代码放在活动子主题(或主题)的function.php文件中。

经过测试和工作。

答案 2 :(得分:0)

我测试了以下解决方案,并且可以在Woocommerce 3.6.3上使用。之后,组产品显示的价格为其所有子产品的总和。


button{
  width: 100px;
}

button span{
  width: 50px;
  overflow: hidden;
  white-space: nowrap;
  display: inline-block;
  text-overflow: ellipsis;
}

button::after {
    font-family: "Font Awesome 5 Brands"; content: "\f099";
  }
<button>
    <span>Some giant text</span>
</button>