wordpress/woocommerce:如果为零则移除价格

wordpress/woocommerce: Remove price if zero

我正忙于 wordpress/woocommerce 网站,我想在产品 category/archive 页面上隐藏价格为零的商品。

我尝试在网络上和 php 文件中查找,但找不到我应该在何处添加 if 语句。

我的 php 知识非常有限。我想知道其他人是否有这方面的经验或者可以以正确的方式帮助我

谢谢!

我还没有测试过,但我希望像这样的东西应该可以完成这项工作。将此添加到您的 functions.php 文件。

add_action('woocommerce_before_shop_loop_item','custom_remove_loop_price');
function custom_remove_loop_price(){
    global $product;
    if(!$product->price){
        remove_action('woocommerce_after_shop_loop_item_title','woocommerce_template_loop_price',10);
    }
}

这个终于为我做到了(使用 woocommerce 3.0.8):

function cw_change_product_price_display( $price ) {
    $clear = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($price))))));
    if($clear == "0 00"){
      return '';
    }
    return $price;
  }
  add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
  add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );

这是另一种方法:

add_filter( 'woocommerce_get_price_html','maybe_hide_price',10,2);
function maybe_hide_price($price_html, $product){
     if($product->get_price()>0){
          return $price_html;
     }
     return '';
 }

此代码适用于 Woocommerce 3.6.3。复制到您的 functions.php

//Hide Price when Price is Zero
add_filter( 'woocommerce_get_price_html','maybe_hide_price',10,2);
function maybe_hide_price($price_html, $product){
     if($product->get_price()>0){
          return $price_html;
     }
     return '';
 } 
// End of above code

尝试了 Jared 的回答,但正如有人所说,一旦满足条件,它就会删除所有价格。最终我采用了这个解决方案,如果价格为 0,它会删除操作,如果不是,则将其添加回去。似乎有效。

public function woocommerce_after_shop_loop_item_title_remove_product_price(){
    global $product;
    $price = floatval( $product->get_price() );
    if( $price <= 0 ){
        remove_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10);
    }else{
        add_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10);
    }
}

add_action( 'woocommerce_after_shop_loop_item_title', 'category_page_changes', 0 );

!is_admin()

add_filter( 'woocommerce_get_price_html','maybe_hide_price',10,2);
function maybe_hide_price($price_html, $product){
     if( $product->get_price() == 0 && !is_admin() ){
          return ''; //or return 'Any text'
     }
     return $price_html;
 }