2017-07-28 1 views
0

Ich arbeite an einem Projekt mit Woocommerce in Wordpress. Ich versuche, alle Produkte einer bestimmten Kategorie zu bekommen, sie in einem Array zu speichern und dann meine Sachen mit ihnen zu machen. Aber auch wenn die Schleife alle Elemente bearbeitet und druckt, wenn ich Daten auf ein Array pushe, behält es nur das letzte bei.Nur das letzte Element wird auf einem Array durch eine Schleife gedrückt

$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); 

Wie Sie sehen können, die Select-I bauen ist diese:

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

Aber der Ausgang des print_r ist diese:

Array 
(
    [0] =&gt; 7814 
) 

Jede Idee, was ich tue, falsch?

Antwort

3

bitte hinzufügen $ countries = array(); vor while-Schleife

<?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); 
?> 
+0

Ich glaube nicht, dass ich eine ganze Stunde nach dem Fehler gesucht habe und es nicht gesehen habe. Vielen Dank. Wird Ihre Antwort akzeptieren, wenn das Zeitlimit vorüber ist – Tasos

+0

Willkommen! Glücklich zu helfen :) –

2

Sie Ihren Array-Variable innerhalb die Schleife initialisiert, so dass Sie ein neues, leeres Array in jeder Iteration erstellen.

$countries = array(); 

gehört vor die while Schleife.

+0

Ich habe die andere Antwort auch kommentiert. Aber ich möchte dir danken. Ich habe deine Antwort aufgewertet, aber ich werde die andere als die beste auswählen, da sie um einige Sekunden schneller war und es nicht richtig ist, sie zu ignorieren. – Tasos

Verwandte Themen