I feel like this shouldn't be that difficult but at the same time, if I can't get it done with my 5 minute PHP knowledge, it might not be as easy as I am expecting this to be.
I have created the following PHP code within my functions.php for my WooCommerce store:
add_filter('woocommerce_add_to_cart_fragments', 'new_cart_count_fragments', 10, 1);
function new_cart_count_fragments($fragments) {
if ( WC()->cart->get_cart_contents_count() < 1) {
$fragments['.cart-count-cat'] = '<span class="count-text">Custom message 1</span>';
} elseif ( WC()->cart->get_cart_contents_count() == 1 ) {
$fragments['.cart-count-cat'] = '<span class="count-text">Custom message 2</span>';
} else {
$fragments['.cart-count-cat'] = '<span class="count-text">Custom message 3</span>';
}
return $fragments;
}
The code does what it's supposed to do. It's not broken, but I'd like to modify it but can't seem to figure out how.
At the moment, it looks for the cart count, and if it's less than 1 adds some text to one of my CSS classes. If I have exactly 1, it displays the second message, and if I have more than 1 product in my cart it displays the final message. All of it is done dynamically thanks to fragments.
Now here's what I've been trying to figure out for hours.
Instead of looking for the overall amount of products in my cart, I'd like to specify a product category and have the code look at how many products I have in my cart of that specific category only.
So let's say I have the categories "x" and "y".
If I have 1 product with the category "x" in the cart and another product with the category "y" and the code only counts the category "x", it should display "Custom message 2".
I hope this makes sense and isn't actually that difficult. Any help is much appreciated 🙏
try this one I also just found this hope it is not yet deprecated.
add_filter('woocommerce_add_to_cart_fragments', 'new_cart_count_fragments', 10, 1);
function new_cart_count_fragments($fragments) {
$product_counter = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
// replace 'x' with your category's slug
if ( has_term( 'x', 'product_cat', $product->id ) ) {
$product_counter++;
}
}
if ( $product_counter < 1) {
$fragments['.cart-count-cat'] = '<span class="count-text">Custom message 1</span>';
} elseif ( $product_counter == 1 ) {
$fragments['.cart-count-cat'] = '<span class="count-text">Custom message 2</span>';
} else {
$fragments['.cart-count-cat'] = '<span class="count-text">Custom message 3</span>';
}
return $fragments;
}