首页 文章

根据Woocommerce中的产品类别隐藏价格

提问于
浏览
2

在Woocommerce中我试图隐藏存档页面上的产品和基于类别的单个产品页面,但条件似乎不起作用,只是隐藏所有价格,无论我是否设置类别

add_filter( 'woocommerce_variable_sale_price_html', 'woocommerce_remove_prices', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'woocommerce_remove_prices', 10, 2 );
add_filter( 'woocommerce_get_price_html', 'woocommerce_remove_prices', 10, 2 );

function woocommerce_remove_prices( $price, $product ) {
     if(is_product_category('sold')){   
        $price = '';
        return $price;
     } 
}

1 回答

  • 1

    要使代码正常工作,您需要对单个产品页面使用 has_term() 条件函数,并且您需要始终在 if 语句之外返回结尾的价格:

    add_filter( 'woocommerce_variable_sale_price_html', 'woocommerce_remove_prices', 10, 2 );
    add_filter( 'woocommerce_variable_price_html', 'woocommerce_remove_prices', 10, 2 );
    add_filter( 'woocommerce_get_price_html', 'woocommerce_remove_prices', 10, 2 );
    function woocommerce_remove_prices( $price, $product ) {
        if( is_product_category('sold') || has_term( 'sold', 'product_cat', $product->get_id() ) )
            $price = '';
    
        return $price;
    }
    

    有用!但是,这不会删除所选产品的变化价格,并且您仍然可以使用添加到购物车按钮 .

    代码位于活动子主题(或活动主题)的function.php文件中 .


    相反,您可以使用以下内容删除该特定产品类别的所有价格,数量按钮和添加到购物车按钮:

    // Specific product category archive pages
    add_action( 'woocommerce_after_shop_loop_item_title', 'hide_loop_product_prices', 1 );
    function hide_loop_product_prices(){
        global $product;
    
        if( is_product_category('sold') ):
    
        // Hide prices
        remove_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
        // Hide add-to-cart button
        remove_action('woocommerce_after_shop_loop_item','woocommerce_template_loop_add_to_cart', 30 );
    
        endif;
    }
    
    // Single product pages
    add_action( 'woocommerce_single_product_summary', 'hide_single_product_prices', 1 );
    function hide_single_product_prices(){
        global $product;
    
        if( has_term( 'sold', 'product_cat', $product->get_id() ) ):
    
        // Hide prices
        remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
    
        // Hide add-to-cart button, quantity buttons (and attributes dorpdowns for variable products)
        if( ! $product->is_type('variable') ){
            remove_action('woocommerce_single_product_summary','woocommerce_template_single_add_to_cart', 30 );
        } else {
            remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
        }
    
        endif;
    }
    

    代码位于活动子主题(或活动主题)的function.php文件中 .

    经过测试和工作 .

相关问题