How to Access Post Data Outside Loop


The easiest way to display and access  post data outside loop is to use the built-in WordPress core function get_post(); However, for more control over the process, check out this nifty little function from WP Recipes:

function get_post_data($postId) {
	global $wpdb;
	return $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID=$postId");
}

Place this function in your functions.php and then add this code to the desired location outside of the loop:

<?php $data = get_post_data(77);
	echo $data->post_date;     // post date
	echo $data->post_title;    // post title
	echo $data->post_content;  // post content
	echo $data->comment_count; // comments number
?>

For the argument of the function, specify the post ID for which you would like to display data. The function will return an array containing all of the available fields for the specified post post_title, date, content, author_id, post_id etc).

Masum Billah has written 326 articles

Hi I am Md. Masum Billah Contributor of this website. I always like to share various things with other. In this website I am sharing web design related tips and tricks, necessary web development tools, source codes for beginner and advance web developer. You may join with us to help other who want to learn web design and development. Thank you for stay with.

Recommended Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>