rebellion asked “How can I access post data outside the loop?”

December 5, 2008 at 8:24 am

A WpRecipes.com regular reader, rebelion, recently asked in the forum how he can access post data outside the loop. After some research, here’s the answer to rebellion question.

To achieve this recipe, paste the following function on the functions.php file from your theme.
This function takes a singles argument, which is the ID of the post you’d like to access data. It will return an array, containing post title, date, content, author id, post id, etc.

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

To use the function, use the following anywhere on your theme files:

<?php
$data = get_post_data(10);
echo $data[0]->post_title; //Print post title
echo $data[0]->post_date; //Print post date
echo $data[0]->comment_count; //Print number of comments 
echo $data[0]->post_content; /Print post content
?>
Tags: