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?