2017-07-28 99 views
0

我正在使用Wordpress中的Woocommerce項目。我嘗試獲取特定類別的所有產品,將它們保存在一個數組中,然後與他們一起完成我的工作。但是,即使循環工作並打印所有項目,當我將數據推送到數組上時,它只保留最後一個。只有最後一個項目保存在一個循環陣列上

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

正如你所看到的,選擇我建立這一個:

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

print_r的輸出是這一個:

Array 
(
    [0] =&gt; 7814 
) 

任何想法,我在做什麼錯誤?

回答

3

請加$ country = array();前while循環

<?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

我不相信我花了整整一個小時尋找錯誤,並沒有看到它。謝謝。當時間限制通過時會接受你的回答 – Tasos

+0

歡迎!高興地幫助:) –

2

要初始化您的數組變量循環,讓你在創建每個迭代一個新的空數組。

$countries = array(); 

屬於之前while循環。

+0

我也評論了其他答案。但我想感謝你。我提出了你的答案,但我會選擇另一個作爲最好的答案,因爲它快了幾秒鐘,並且忽略它是不對的。 – Tasos

相關問題