3

I am trying to get a list of a custom post type's IDs using WP_Query, but it is returning undesired result, which is a memory leak and stuck browser.

Here is the code I use:

    $the_query = new WP_Query("post_type=post&posts_per_page=-1&field=ids");    
    if ($the_query->have_posts()) {
      while ($the_query->have_posts()){
         echo get_the_ID();
      }
    }

It makes my browser infinitely trying to load the page. May be somebody know what's wrong with the code above..

3

You are missing the the_post() function call in the loop. Just add

$the_query->the_post();

in your loop. Apart from that, your loop should work

EDIT

You should also not forget to reset your postdata after the query is done

4
  • aw, seem a noob's mistake. but I now get a bunch of this kind of message Notice: Trying to get property of non-object in X:\xxxx\xxxxxxxxxxxx\wp-includes\query.php on line 4601. What would be another problem?
    – Ari
    Sep 8 '15 at 5:09
  • I think that you might have misplaced the the_post() function call. I cannot see anything in your code that would suggest the issue. All seems fine Sep 8 '15 at 5:14
  • that's alright now, just another mistake that I didn't noticed, I shouldn't add s to the field argument's key.
    – Ari
    Sep 8 '15 at 5:16
  • Ag crap yes, I also missed that. Glad you found it. Enjoy ;-) Sep 8 '15 at 5:20
4

I know you want solution "using WP_Query", but why not use get_posts() for this?

$posts_ids = get_posts('post_type=post&posts_per_page=-1&fields=ids');
// $posts_ids is now an array of IDs
echo implode(',', $posts_ids); // prints: 123, 124, 125, 126, ...

// or

foreach( $posts_ids as $id ) {
    echo $id;
}
5
  • get_posts uses WP_Query to return an array of posts, so the odds remain the same whether you are using one or the other. The main difference is, get_posts return only the $posts property from the query object and not the complete query object, and get_posts breaks pagination legally by passing no_found_rows=true to WP_Query Sep 8 '15 at 6:15
  • Yeah, I know, but if the goal is "retrieve only IDs", than with WP_Query you have to the_post() it, and then wp_reset_postdata() it ... so two more steps, that can be forgotten ;)
    – Marek
    Sep 8 '15 at 6:40
  • is it faster than using WP_Query?
    – Ari
    Sep 8 '15 at 12:47
  • I don't think so. It's fewer lines of code ... and maybe it's more efficient, so about few miliseconds faster, too. Nothing you will notice.
    – Marek
    Sep 8 '15 at 18:28
  • This works by coincidence. get_posts has only array as a valid input type in its documentation. It works by coincidence since get_posts passes the input to wp_parse_args but I would warn against using a WP function counter to its documentation. Jan 13 at 18:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.