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

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
?>

15 Responses

Dec 05 2008 13:02

The function can be improved in this way:

return $wpdb->get_row(“SELECT * FROM $wpdb->posts WHERE ID=$postId”);

so you can get post values more simply:

echo $data->post_title; //Print post title

However, you can also use the WP core function get_post()
http://codex.wordpress.org/Function_Reference/get_post
that does the same thing.

Dec 05 2008 13:12

Thanks for your improvements! I have used get_post() in the past but I didn’t remember it does exactly the same thing as the function here does.

Dec 05 2008 13:27

You can compare the two functions output in this way

$data1 = get_post_data(10);
$data2 = get_post(10);

print_r($data1);
echo ”;
print_r($data2);

I think they do both exactly the same thing :-)

Dec 05 2008 13:32

Yes they does :) Thanks for letting me know about that!

Dec 05 2008 13:33

you’re welcome!

Dec 05 2008 14:04

I asked a question too.. but I used the contact form instead of the forum… I hope it gets answered :)

Dec 05 2008 14:44

@Popular Technology: Why asking a question by email when you know that the forum is here for recipe requests?

Dec 05 2008 17:39

Salut Jean-Baptiste. En lisant ce billet j’ai eu envie de poster un article qui donne encore d’autres alternatives (dont une plus simple). Si tu veux y jeter un oeil ;)

http://www.webinventif.fr/wordpress-hors-boucle/

Dec 05 2008 19:32

Thanks for answering this question! :) But what if I want to get the category and tags that the post is linked to?

Dec 06 2008 08:29

One of my buddies is always talking about your blog at work – finally came and checked it out today, nice work! I’m subscribing to your rss feed – keep on posting!

Dec 06 2008 10:01

@rebellion: That will be answered soon :)

Dec 10 2008 02:23

there is also a problem for me too. how to get the permalink for a post selected like that… do you have any suggestions?

Dec 10 2008 12:03

@stratosg: I’ll write a recipe about that soon :)

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required