0

I'm using this PHP to get all the product category slugs on a single product page:

global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
if(is_array($terms)){
foreach ($terms as $term) {
    $product_cat_slug = $term->slug;
    $product_cat_slugs = ' product_cat-' . $product_cat_slug;
    echo $product_cat_slugs;
}
}

The line echo $product_cat_slugs; outputs product_cat-category1 product_cat-category2, which I will use for div classes.

The problem is that when I delete the echo $product_cat_slugs; from the function above and use <?php echo $product_cat_slugs; ?> elsewhere on the page, all I get for output is the last category slug product_cat-category2, and not both categories product_cat-category1 product_cat-category2.

What's wrong? It appears that $product_cat_slugs is overwritten when outside the foreach; how can I prevent that?

1 Answer 1

-1

You are overwriting $product_cat_slugs on every iteration of your loop - so when it's finished, that variable will be set to the last value.

Why not do all of your outputs inside that loop?

Or if for some reason you don't want to do that, make $product_cat_slugs an array instead of a variable:

$product_cat_slugs = [];
foreach ($terms as $term) {
    $product_cat_slug = $term->slug;
    $product_cat_slugs[] = ' product_cat-' . $product_cat_slug;
}
5
  • Thanks, but that either gives me no output, or the error Array to string conversion with echo $product_cat_slugs; outside the loop. Dec 6, 2021 at 22:55
  • You need to learn how arrays work in PHP I think.
    – vancoder
    Dec 7, 2021 at 16:06
  • That's what we're here for, to learn :) Or at least I am. Dec 7, 2021 at 17:19
  • Then you are in the wrong place to learn basic PHP, but I appreciate the downvote for trying to help you.
    – vancoder
    Dec 7, 2021 at 21:09
  • You're blaming me for your example not working? Dec 8, 2021 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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