Tasos
Tasos

Reputation: 7587

Only last item is kept on an array push through a loop

I am working on a project with Woocommerce in Wordpress. I try to get all the products of a specific category, save them in an array and then do my things with them. However, even if the loop works and prints all the items, when I push data on an array, it keeps only the last one.

$args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'additional-number' );
$loop = new WP_Query( $args );

echo '<select class="form-control">';
echo '<option>Select a country</option>';
while ( $loop->have_posts() ) : $loop->the_post();
    global $product; 
    $countries = array(); 
    $countries[] = $product->id;
    echo '<option value="' . $product->id . '">' . $product->post->post_title . '</option>';
endwhile; 
echo '</select>';
wp_reset_query(); 
print_r($countries);

As you can see, the select I build is this one:

<select class="form-control">
    <option>Select a country</option>
    <option value="7818">England</option>
    <option value="7814">Germany</option>
</select>

But the output of the print_r is this one:

Array
(
    [0] =&gt; 7814
)

Any idea what I am doing wrong?

Upvotes: 0

Views: 283

Answers (2)

C3roe
C3roe

Reputation: 96424

You are initializing your array variable inside the loop, so that you create a new, empty array in each iteration.

$countries = array();

belongs before the while loop.

Upvotes: 2

Shital Marakana
Shital Marakana

Reputation: 2887

please add $countries = array(); before while loop

<?php
$args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'additional-number' );
$loop = new WP_Query( $args );
$countries = array(); 
echo '<select class="form-control">';
echo '<option>Select a country</option>';
while ( $loop->have_posts() ) : $loop->the_post();
    global $product; 
    $countries[] = $product->id;
    echo '<option value="' . $product->id . '">' . $product->post->post_title . '</option>';
endwhile; 
echo '</select>';
wp_reset_query(); 
print_r($countries);
?>

Upvotes: 3

Related Questions