隐藏购物车中“ WooCommerce”产品类别的“删除商品”

时间:2019-01-04 04:41:26

标签: php wordpress woocommerce product cart

我想在WooCommerce中针对特定产品类别从购物车中隐藏“删除商品”,就像在“ Hide "remove item" from cart for a specific product in WooCommerce”应答线程中一样,但针对特定产品类别。< / p>

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

以下代码将针对特定产品类别从购物车隐藏“删除商品” (您将在第二个功能中定义)

// Custom conditional function that checks for categories (including parent)
function has_product_categories( $product_id, $categories ) {
     // Initializing
    $parent_term_ids = $categories_ids = array();
    $taxonomy        = 'product_cat';

    // Convert categories term names and slugs to categories term ids
    foreach ( $categories as $category ){
        if( is_numeric( $category ) ) {
            $categories_ids[] = (int) $category;
        } elseif ( term_exists( sanitize_title( $category ), $taxonomy ) ) {
            $categories_ids[] = get_term_by( 'slug', sanitize_title( $category ), $taxonomy )->term_id;
        }
    }

    // Loop through the current product category terms to get only parent main category term
    foreach( get_the_terms( $product_id, $taxonomy ) as $term ){
        if( $term->parent > 0 ){
            $parent_term_ids[] = $term->parent; // Set the parent product category
            $parent_term_ids[] = $term->term_id; // (and the child)
        } else {
            $parent_term_ids[] = $term->term_id; // It is the Main category term and we set it.
        }
    }
    return array_intersect( $categories_ids, array_unique($parent_term_ids) ) ? true : false;
}

// Hiding "remove item" for specific product category
add_filter('woocommerce_cart_item_remove_link', 'filter_cart_item_remove_link', 20, 2 );
function filter_cart_item_remove_link( $button_link, $cart_item_key ){
    // HERE your specific products categories
    $categories = array( 'clothing' );

    // Get the current cart item
    $cart_item = WC()->cart->get_cart()[$cart_item_key];

    // If the targeted product is in cart we remove the button link
    if( has_product_categories( $cart_item['product_id'], $categories ) )
        $button_link = '';

    return $button_link;
}

代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。

答案 1 :(得分:0)

下面的代码将按您希望的方式工作:只需更改 if 子句中的类别ID:

function tristup_woocommerce_cart_item_remove_link($link){
    preg_match('/data-product_id=\"(.*?)\"/', $link, $matches);

    $flag=0;
    if($matches)
    {
        $product_id=$matches[1];
        $terms = get_the_terms ( $product_id, 'product_cat' );
        foreach ( $terms as $term ) 
        {
            if($term->term_id=='210') // change with your category id or add more with in proper syntaxes
            {
                return '';              
            }
        }

    }  
    return $link;       
}
add_filter('woocommerce_cart_item_remove_link', 'tristup_woocommerce_cart_item_remove_link');