How to get an array of post data from wp_query result?

  • When run a query with WP_Query method, I got an object. I understand that I can then do the loop to display stuffs. But, my goal is not to display anything, instead, I want to get some post data by doing something like "foreach...". How can I get an array of post data that I can loop through and get data?

    An important difference to keep in mind between accessing post data directly versus using template tags is that filters are not applied to the data and some functionality may break.

  • rofflox

    rofflox Correct answer

    8 years ago

    You should read the function reference for WP_Query on the WordPress codex. There you have a lot of examples to look at. If you don't want to loop over the result set using a while, you could get all posts returned by the query with the WP_Query in the property posts.

    For example

    $query = new WP_Query( array( 'post_type' => 'page' ) );
    $posts = $query->posts;
    foreach($posts as $post) {
        // Do your stuff, e.g.
        // echo $post->post_name;

    None of the examples you link to demonstrates how to process posts, though. So it's good that you answered, pity they don't have it in the documentation. Another tip: If you're doing a match on a unique post you can use a function like this with `'posts_per_page'=>1` in args. `function wp_queryfirstpost($args) { $q=new WP_Query($args); $pp=$q->get_posts(); $firstpost=false;if ($pp) $firstpost=$pp[0]; wp_reset_postdata(); return $firstpost; }`

    @rofflox: You are a saint! Great for circumventing get_the_title/ID/younameit.

    You should use `$query->posts` instead, `$query->get_posts()` will trigger a re-running of the query parsing and additional unnecessary database queries

    $query->get_posts(); is not working as expected. Not sure why but it returns fewer post than the query. See here:

    This answer is plain wrong, when you create a new WP_Query with some arguments the method get_posts() is internally called right away and you SHOULD NOT CALL IT AGAIN! If you call it again as shown in the example above it will run a DIFFERENT query, depending on the arguments and results form the initial run (internal flags set, etc..), and can potentially return a different (smaller) set of results or no results at all. As TomJNowell and Laxmana suggested above one should use $query->posts to get the post data.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM