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?

Related posts

Leave a Reply

3 comments

  1. 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;
    }
    
  2. Actually, you don’t need to refuse to use while() loop. Same WP_Post Object is already stored in post property:

    $query = new WP_Query( $args );
    
    if ( $query->have_posts() ) {
    
        // some code here if you want.
    
        while ( $query->have_posts() ) {
    
            $query->the_post();
    
            // now $query->post is WP_Post Object, use:
            // $query->post->ID, $query->post->post_title, etc.
    
        }
                    
    }