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.
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
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.
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.
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
Yes they does
Thanks for letting me know about that!
you’re welcome!
I asked a question too.. but I used the contact form instead of the forum… I hope it gets answered
@Popular Technology: Why asking a question by email when you know that the forum is here for recipe requests?
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/
Thanks for answering this question!
But what if I want to get the category and tags that the post is linked to?
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!
@rebellion: That will be answered soon
there is also a problem for me too. how to get the permalink for a post selected like that… do you have any suggestions?
@stratosg: I’ll write a recipe about that soon
Trackbacks: