Accessing the post content with WP_Query

First of all, don’t use and abuse the $wp_query global variable. This global should be reserved to the main query only. Use any other variable that will not create conflict.

Secondly, don’t use the raw WP_Post properties. These are raw and unfiltered. WP_Query does set up postdata by default which make the use of the template tags possible.

Thirdly, always reset all instances of WP_Query to avoid any conflict with other queries on the same page

Fourthly, you have a syntax error in this line <?php echo $wp_query->post_title.'<br>';. You are missing a closing php tag

You can rewrite your code to something like this

 $args = array(
  'post_type'      => 'post',
  'posts_per_page' => $count,
  'paged'          => $paged,
);
$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) { 
    $query->the_post();
        the_title();
        the_content();
    }
    wp_reset_postdata();
}

EDIT

If you need to access the WP_Post properties directly, you can use for instance

echo apply_filters( 'the_content', $query->post_content );

to display the post content,

echo apply_filters( 'the_title', $query->post_title );

will display the post title. The post status can be accessed by

$query->post_status

See a list of all available properties here

You have to remember, there are template tags that are available during the loop to display these info without using the WP_Post properties

Leave a Comment