0

Depending on the product category, I have different data to display on category page. I'm getting my category ID this way:

<?php global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
    $product_cat_id = $term->term_id;
    break;
}

if ($product_cat_id == "6") {
echo "aaa";
}
elseif ($product_cat_id == "7") {
echo "bbb";
}
?>

But I need to display different data when product is in two categories and it does not work.

echo $product_cat_id;

It recognizes only one category. How do I make it recognize two and make IF statement for product which is in category 6 AND 7?

2 Answers 2

1

Try This Code

        <?php global $post;
    $terms = get_the_terms( $post->ID, 'product_cat' );
    foreach ($terms as $term) {
        $product_cat_id = $term->term_id;
        break;
    }

    if ($product_cat_id == "6" && $product_cat_id == "7" ) {
    echo "aaabbb";
    }
 else if ($product_cat_id == "6"  ) {
    echo "aaa";
    }
    else if ($product_cat_id == "7") {
    echo "bbb";
    }
    ?>
0

Your $product_cat_id is an array() of all of your categories and it looks like you are only running the if statement outside of the array to check the category's ID. Instead, you should run it inside the foreach loop. This is untested, but it should look something like this:

<?php
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ( $terms as $term ) {
    $product_cat_id = $term->term_id;
    break;
}

foreach ( $product_cat_id as $key => $value ) {
    if ( $value == "6" ) {
        echo "aaa";
    }
    if ( $value == "7" ) {
        echo "bbb";
    }
}
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.