从WPQuery中获取数组

时间:2018-08-13 作者:Alt C

我有一个这样的查询,我将获得产品的id。这很好:

function ids(){
    $args = array(
        \'numberposts\'   => -1,
        \'post_type\'     => \'product\',
        \'meta_key\'      => \'wppl_is_dax\',
        \'meta_value\'    => \'1\'
    );


    // query
    $the_query = new WP_Query( $args );


                if( $the_query->have_posts() ): while( $the_query->have_posts() ) : $the_query->the_post();
                global $product;
                return $product->get_id();
                endwhile; endif; wp_reset_query();

}
但是现在我想在下面的中使用上面查询的输出

function tester2(){

 $targetted_products = array(/* the ids from above function- ids()*/);

}
如果我使用$targeted\\u products=数组(ids()),我只能获得一个id;

3 个回复
最合适的回答,由SO网友:Castiblanco 整理而成

您的函数返回$product->get_id();, 相反,您应该将这些值保存到一个数组中,并在最后返回该数组。

function ids(){
    $args = array(
        \'numberposts\'   => -1,
        \'post_type\'     => \'product\',
        \'meta_key\'      => \'wppl_is_dax\',
        \'meta_value\'    => \'1\'
    );


    // query
    $the_query = new WP_Query( $args );
    $allIds = array();

            if( $the_query->have_posts() ): while( $the_query->have_posts() ) : $the_query->the_post();
                global $product;
                array_push($allIds,$product->get_id());
                endwhile; endif; wp_reset_query();
    return $allIds;
}

SO网友:Milo

如果只需要ID,那么如果使用fields 参数以仅在数组中获取该字段:

function ids(){
    $args = array(
        \'numberposts\'   => -1,
        \'post_type\'     => \'product\',
        \'meta_key\'      => \'wppl_is_dax\',
        \'meta_value\'    => \'1\'
        \'fields\'        => \'ids\'
    );
    $the_query = new WP_Query( $args );
    if( $the_query->have_posts() ){
        return $the_query->posts;
    }
    return false;
}

SO网友:Valerii Vasyliev
function ids(){

    $args = array(
        \'numberposts\'   => -1,
        \'post_type\'     => \'product\',
        \'meta_key\'      => \'wppl_is_dax\',
        \'meta_value\'    => \'1\'
    );


      // query
      $the_query = new WP_Query( $args );

      $post_ids = [];

      if( $the_query->have_posts() ): 

         $post_ids = wp_list_pluck( $the_query->posts, \'ID\' );

      endif; 

      wp_reset_query();


      return $post_ids;
}

read more https://codex.wordpress.org/Function_Reference/wp_list_pluck

结束