BlueDogRanch
BlueDogRanch

Reputation: 536

PHP variable gets overwritten in foreeach loop with last item

I've looked at other "PHP variable overwritten" answers and still can't figure this out.

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.

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? $product_cat_slugs seems to be overwritten when outside the foreach; how can I prevent that?

How do I output product_cat-category1 product_cat-category2 outside of the loop?

Upvotes: 0

Views: 48

Answers (1)

Mitchell Bennett
Mitchell Bennett

Reputation: 132

Might I suggest to append the string, such as

global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );

if( is_array( $terms ) ) {
    $product_cat_slugs = ''; //Define the variable outside of the loop
    foreach ( $terms as $term ) {
        $product_cat_slugs .= ' product_cat-' . $term->slug; //Append the slug onto the string that already exists
    }
    echo $product_cat_slugs; //Echo the string outside of the loop so it only occurs once.
}

Upvotes: 3

Related Questions