隐藏购物车中“ WooCommerce”产品类别的“删除商品” [英] Hide “remove item” from cart for WooCommerce product category

查看:60
本文介绍了隐藏购物车中“ WooCommerce”产品类别的“删除商品”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在WooCommerce中针对特定产品类别从购物车中隐藏删除商品,就像在 在WooCommerce中为特定产品从购物车中隐藏从购物车中删除项目 答案线程,但是

I would like to Hide "remove item" from cart for a specific product category in WooCommerce, just like in "Hide "remove item" from cart for a specific product in WooCommerce" answer thread, but for a specific product category.

我们将不胜感激。

推荐答案

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

The following code will hide "remove item" from cart for a specific product category (that you will define in the 2nd function):

// 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文件)。经过测试,可以正常工作。

Code goes in function.php file of your active child theme (or active theme). Tested and works.

这篇关于隐藏购物车中“ WooCommerce”产品类别的“删除商品”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆