2015-06-03 192 views
1

所以,我似乎無法理解爲什麼我不能回到我的數組返回數組PHP

調用該函數

<?php 

$args = array('post_type' => 'product', 
       'stock' => 1, 
       'posts_per_page' => 12, 
       'meta_key' => 'total_sales', 
       'orderby' => 'meta_value_num'); 

productsLoop($args); 

?> 

位於functions.php的功能

function productsLoop($args){ 

$post_ids = array(); 
    $loop = new WP_Query($args); 
    if ($loop->have_posts()) { 
    while ($loop->have_posts()) : $loop->the_post(); 


    $post_ids[] = get_the_ID(); 


    endwhile; 
    } else { 
    echo __('No products found'); 
    } 

    wp_reset_query(); 
    return $post_ids; 
} 

然後在原始頁面上,我在每個循環中使用a中的$ post_ids,但它返回未定義varibale的錯誤

+0

你也可以發佈錯誤? – STLMikey

+0

這就是它 - >「注意:未定義變量:post_ids」 – user2389087

回答

3

$post_ids變量在函數外部不可用。由於該函數返回ID數組,因此可以將該返回值分配給變量並在循環中使用它。

$ids = productsLoop($args); 
// you can use the $ids variable now, for example... 
foreach ($ids as $id) { 
    echo $id . '<br>'; 
} 

請仔細閱讀PHP手冊的variable scope部分以瞭解詳細信息。