Sign up ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
It's no clear what you want. Please explain your main goal a bit better and post your current state of code here. –  rofflox Aug 11 '12 at 8:17
sorry for the confusing, I just edited my question. –  Jenny Aug 11 '12 at 8:25

2 Answers 2

up vote 18 down vote accepted

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 resultset using a while, you could get all posts returned by the query with the WP_Query class method get_posts().

For example

$query = new WP_Query(array('post_type' => 'page'));
$posts = $query->get_posts();

foreach($posts as $post) {
    // Do your stuff, e.g.
    // echo $post->post_name;
share|improve this answer
That helps! Exactly what I need, thanks! –  Jenny Aug 11 '12 at 8:40
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; } –  Henrik Erlandsson Mar 21 '14 at 9:38
@rofflox: You are a saint! Great for circumventing get_the_title/ID/younameit. –  Vicky Apr 30 at 17:39

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

            while ( $query->have_posts() ) {


                // now $query->post is WP_Post Object, use:
                // $query->post->ID, $query->post->post_title, etc.


share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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