Home > OS >  How do I make this condition actually work, I am using woocommerce
How do I make this condition actually work, I am using woocommerce

Time:11-18

Basically I am trying to create a condition where if a product is equal to a specific subcategory which is 2 other categories (specifically garden & roof) in this case.

I am trying to make it where if the product is not equal to the housing category it will print the cart addition which is a add to cart button. This does not work for some reason, and also I need help with a continuation statement (else, elseif) for if the product is actually the housing category it will just do nothing and not print that small form but actually let that sites page still function and load.

<div >
<?php 
    if ($product->get_categories() != "housing") {
        $action = 'woocommerce_cart_addition_form';
} ?>
</div>

I tried many types of if, else loops etc with different ways of using the loops but so many of the times it would just make my site crash and not load that specific page... I am expecting it to where if it detects housing as a category that the customer opens it will not allow them to add to cart, but if it detects another two categories which could be garden or roof, it will allow the customer to see the add to cart function and use it.

CodePudding user response:


$terms = $product->get_categories(); ///< it gives an array of 

// i check if "housing" is an element of the array containing only category names
if (!in_array("housing", $terms) { 
   $action = 'woocommerce_cart_addition_form';
}

in_array: is used to check if an element exists in an array.

check https://woocommerce.github.io/code-reference/classes/WC-Abstract-Legacy-Product.html#method_get_categories for get_categories

CodePudding user response:

has_term function will be best to make check your need. However I don't understand the other part related to the action thing, but for the category exists/linked check you should use has_term. You need to pass the terms slugs array or single term and taxonomy name and product id.

So the code will look like this:

<div >
<?php 
if ( has_term( ['housing'], 'product_cat', $product->get_id() ) ) {
    $action = 'woocommerce_cart_addition_form';
}
?>
</div>
  • Related