Reputation: 94
This is a new question with the same requirements that the following answer already given in:
Checking that one of multiple mandatory products categories are in cart
But it does not seem to work for me and I get an error on this line:
if( !WC()->cart->is_empty() && ( is_cart() || is_product_category(
$categories_needed[0] || is_product_category( $categories_needed[1] ) )
){
I get the error that there is an unexpected
{
Any help is appreciated.
Upvotes: 2
Views: 244
Reputation: 253887
There is just 2 small mistakes:
1) A missing ;
at the end of return $categories
so in this updated code:
// Function that define the mandatory product category
function your_mandatory_category_slug(){
// DEFINE HERE the 2 SLUGs of the needed product categories
$categories = array('cxsuite-download-option','cxsuite-hosted-option');
return $categories; // <== HERE
}
2) An missing closing )
in is_product_category( $categories_needed[0]
so in this updated code:
// Function that display a message if there is not in cart a mandatory product category
function mandatory_category_display_message() {
$categories_needed = your_mandatory_category_slug();
// check that cart is not empty (for cart and product category archives)
if( !WC()->cart->is_empty() && ( is_cart() || is_product_category( $categories_needed[0] ) || is_product_category( $categories_needed[1] ) ) ){
$category_name = array();
$category_url = array();
// iterating both categories
foreach($categories_needed as $key => $category_needed){
$category_obj = get_term_by( 'slug', $category_needed, 'product_cat' );
if ( is_wp_error( $category_obj ) )
return;
$category_name[$key] = $category_obj->name;
$category_url[$key] = get_term_link( $category_needed, 'product_cat' );
}
// Display message when one of the product categories is not in cart items
if ( !has_mandatory_category() ) {
// render a notice to explain why checkout is blocked
wc_add_notice( sprintf( __( '<strong>Reminder:</strong> You have to add in your cart, a product from "%1$s" or from "%3$s" category, to be allowed to check out. Please return <a href="%2$s"> here to "%1$s"</a> or <a href="%4$s"> here to "%3$s"</a> product pages', 'your_theme_domain'), $category_name[0], $category_url[0], $category_name[1], $category_url[1] ), 'error' );
}
}
}
add_action( 'woocommerce_before_main_content', 'mandatory_category_display_message', 30 ); // for product mandatory category archives pages
add_action( 'woocommerce_check_cart_items', 'mandatory_category_display_message' ); // for cart page
Now it should work without errors…
Upvotes: 2