0

My code is:

<?php
//Get posts by the arguments saved in the $args array
$vendor_postlist = get_posts( $args );

// Loop the list of posts obtained and for each post extract its product category and save it in an array
foreach ( $vendor_postlist as $post ){  

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

foreach ( $terms as $term ) {
$categories[] = $term->name;
echo $term->name;
}

unset( $term );
}

unset( $post );
print_r($categories);
?>

A little background info: I am trying to create a shortcode that will display a list of (Woocommerce) products in a table. So $args stores the arguments such as the author of the post, the post type etc, some of them being extracted from the shortcode attributes.

The issue seems to be in the second foreach loop:

foreach ( $terms as $term ) {
$categories[] = $term->name;
echo $term->name;
}

The echo is only for checking if it displays correctly at this point the terms it's supposed to display. And indeed the list of terms displayed is correct.

Example: Fruits, Vegetables, Flowers

But when I use print_r($categories) - which was supposed to display an array with the three categories - only the last category appears to have been stored in the array: Array ( [0] => Flowers)

I need to generate a table for each category, that's why I am trying to create the array of categories, but I'm stuck on this point, having no idea what could be wrong.

If someone knows, please let me know. I would be very happy to solve this issue. Thank you!

closed as off-topic by Michael, cjbj, fuxia Feb 26 '17 at 2:48

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

2

Try this code. is it necessary to unset that arrays in foreach? unset inside loop will remove the previous array values.

<?php
    //Get posts by the arguments saved in the $args array
    $vendor_postlist = get_posts( $args );
    $categories = array();
    // Loop the list of posts obt.....
    foreach ( $vendor_postlist as $post ){  

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


    foreach ( $terms as $term ) {
    $categories[] = $term->name;
    echo $term->name;
    }

    }

    print_r($categories);
    ?>
  • 1
    Thank you, Abdul! You are right! Moving the line: $categories = array(); before the first loop solves the issue! Now the array stores all 3 items. It goes to show how inexperienced I am with coding. – Ami Feb 10 '17 at 23:03
  • Oh, and about the unset: I tested and it seems there's no difference if I use them or not. Thank you so much for your useful answer! – Ami Feb 10 '17 at 23:07

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