3

I have a query like this i will get the id's for product. This works fine:

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

}

But now i want to use the output from the above query in the below

function tester2(){

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

}

I am only getting one id if i use $targetted_products =array(ids());

3 Answers 3

0

Your function returns $product->get_id();, instead of that, you should save those values into an array and at the end return that array.

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;
}
0
6

If you only want IDs, the query will consume much less memory if you use the fields parameter to just get that one field back in an array:

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;
}
1
  • 1
    This is better than the accepted answer.
    – Fayaz
    Commented Aug 14, 2018 at 2:38
1
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.