Skip to content
Advertisement

Hide “remove item” from cart for WooCommerce product category

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.

Any help would be appreciated.

Advertisement

Answer

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 handle parent product categories too
function has_product_categories( $categories, $product_id = 0 ) {
    $parent_term_ids = $categories_ids = array(); // Initializing
    $taxonomy        = 'product_cat';
    $product_id      = $product_id == 0 ? get_the_id() : $product_id;

    if( is_string( $categories ) ) {
        $categories = (array) $categories; // Convert string to array
    }

    // Convert categories term names and slugs to categories term ids
    foreach ( $categories as $category ){
        $result = (array) term_exists( $category, $taxonomy );
        if ( ! empty( $result ) ) {
            $categories_ids[] = reset($result);
        }
    }

    // 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;
}

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement