How to load WordPress posts using WP_Query

Spread the love

In order to use WordPress methods directly to pull posts or any other data, “wp-load.php” file from the active WordPress installation is required to be included in custom php.

require($_SERVER['DOCUMENT_ROOT'] . '/../www/wp-load.php');

Following code snippet shows how to load a posts details using WP_Query.

$args = array(
'p'=> $_REQUEST['postid'], // ID of a page, post, or custom type
'post_type'=> 'any'
);

The above code is creating an arguments array to get the post by a specific post id.
If you want to pull the latest post, following arguments can be used.

$args = array(
'numberposts' => 1, //Numbers of posts to be pulled
'offset' => 0, //Start Index
'orderby'=> 'post_date', //Sort the posts by published date
'order'=> 'DESC', //Sort order, ACS/DESC
'post_type'=> 'post', //Type of the post(s) to be pulled
'post_status'=> 'publish', //Status of the post, draft/publish
'suppress_filters'=> true
);

$latest_posts = new WP_Query( $args );
$latest_posts->have_posts();
$latest_posts->the_post();

The above code loads the post details based on the arguments passed. In this example we’re assuming that only one post has been loaded using the post id. Different properties of the post can be accessible using following WordPress methods:

the_title(); //Displays the Title of the Post
the_time('F j, Y'); //Displays the publish date/time of the post, different PHP Date Time format can be used
the_content(); //Displays the body of the post with formatting
the_excerpt(); //Displays the summary of the post with ReadMore link