Query or show a specific post in wordpress

If you are looking for php code or a plugin for your WordPress that takes a post ID and returns the database record for that post then read on. This is very helpful when you want to show a specific post on your homepage or other pages to get more attention. It allows you to design your homepage or a page with the post(s) that you want to be shown on the page rather than the 10 recent posts that the WordPress automatically chooses for you.

PHP Code Example to Query a WordPress Post

Example 1

The following code will Query the post with post id 26 and Show the title and the content.

<?php
$post_id = 26;
$queried_post = get_post($post_id);
$title = $queried_post->post_title;
echo $title;
echo $queried_post->post_content;
?>

Example 2

The following style could be more useful as it lets the user customise the font easily.

<?php
$post_id = 26;
$queried_post = get_post($post_id);
?>
<h2><?php echo $queried_post->post_title; ?></h2>
<?php echo $queried_post->post_content; ?>

Example 3

Using an Array… The following code will query every post number in ‘thePostIdArray’ and show the title of those posts.

<?php $thePostIdArray = array("28","74", "82", "92"); ?>
<?php $limit = 4 ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); $counter++; ?>
<?php if ( $counter < $limit + 1 ): ?>
<div class="post" id="post-<?php the_ID(); ?>">
<?php $post_id = $thePostIdArray[$counter-1]; ?>
<?php $queried_post = get_post($post_id); ?>
<h2><?php echo $queried_post->post_title; ?></h2>
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>

How to Display the Post Content Like WordPress

When you retrieve the post content from the database you get the unfiltered content. If you want to achieve the same output like WordPress does in its’ posts or pages then you need to apply filter to the content. You can use the following code:

<?php
$post_id = 26;
$queried_post = get_post($post_id);
$content = $queried_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
echo $content;
?>

For a range of all the returned fields that you can use, check the WordPress site here.

Find out if we are in a particular WordPress post

Lets say you want to apply some custom tweak when a particular post is being viewed. You will need to programmatically determine when you are in this specific post (example: Post ID 2). The following snippet of code will be helpful for this:

if (is_single("2"))
{
//Do your custom tweak for post whose ID is 2
}

You can do the same thing for pages too (5 is the page ID in this example):

if (is_page("5"))
{
//Do your custom tweak for post whose ID is 2
}

Query X Number of Recent Posts

You can use the “wp_get_recent_posts” function to retrieve X number of recent posts and then display them however you want to. Here is an example:

<?php
//Query 5 recent published post in descending order
$args = array( 'numberposts' => '5', 'order' => 'DESC','post_status' => 'publish' );
$recent_posts = wp_get_recent_posts( $args );
//Now lets do something with these posts
foreach( $recent_posts as $recent )
{
    echo 'Post ID: '.$recent["ID"];
    echo 'Post URL: '.get_permalink($recent["ID"]);
    echo 'Post Title: '.$recent["post_title"];
    //Do whatever else you please with this WordPress post
}
?>

Using a Plugin to List all Posts Alphabetically

You can also use the WP Alphabetic Listing WordPress plugin to list all your posts.

Getting the URL of a post/page

The post/page object that you retrieve using the get_post() function doesn’t actually have the URL of the post. It does have a guid file which contains the URL but that one is not reliable. Use the following function to get the URL value of the post/page:

$post_id = '26';
$post_url = get_permalink($post_id);

Found this resource interesting? Subscribe to Tips and Tricks HQ

email icon rss feed icon twitter icon google plus icon

Comments (87 responses)

  1. admin says:

    @RW, You can show the title of the post like the following:

    $title = $queried_post->post_title;
    echo $title;

    After you query the post and get the data, you can show it however you like it. Yes you can even do it from a WordPress shortcode too.

  2. RW says:

    How can I add Title to this example?

    post_content;
    $content = apply_filters(‘the_content’, $content);
    $content = str_replace(‘]]>’, ‘]]>’, $content);
    echo $content;

    Thanks,
    Bob

  3. Ansy says:

    After a long search I found this and its working .. Thanks a lot.

  4. Santosh says:

    Thanks its very helpfull .. :)

  5. Tom Frearson says:

    Really helpful guide, especially the part about using the filters.

    Many thanks!

  6. Ramesh singh says:

    Hello. I m fresher in PHP..It helped me so much in fetching single post in wordpress…Thanks a lot!!!

  7. kumar says:

    it saved my day . . thnx for this man

  8. Thank you! Worked like charm! With some trixing i got the title and meta’s right as well :)

  9. Jeyakumar says:

    Thanks for post this article .. This article saved my time.Keep posting like this

  10. Hi! Thanks a lot for this very particular and helpful code snippet. It couldn’t be clearer, or more helpful.

  11. admin says:


    <?php
    $key_1_value = get_post_meta('POST-ID', 'Key_1', true); //Use this to retrieve the plain custom field value. Example: 1117,302,1309
    $thePostIdArray = explode(",", $key_1_value); //Load the customer field value into an array (each comma will separate an item)
    print_r($thePostIdArray); //Lets check the value of this array
    ?>

  12. Andre says:

    For:

    $thePostIdArray = array(“28″,”74″, “82″, “92″);

    How would I make the post id’s be loaded from a custom field in WordPress?

    For example I want to make a custom post type, and a field where a user can enter in order post ID’s.

    Like this: 1117,302,1309 – and these will then dynamically be placed in the array?

    Is this possible?

    The post type, and field is easy, I’m just not sure on how to pass the ID’s from the field into the array.

    thoughts?

  13. admin says:

    First you would add the image URL as a custom field in that post. Then you can retrieve the value of that custom field and use it to show the image. Are you using a custom field?

  14. Hi,

    I wonder how to show the thumbnail image of the the post with example 2. Everything works but I dont know how to show the image of the post.’

    Do you know how to display the image aswell?

  15. Sanam Maharjan says:

    Thanks a lot. Worked as a charm :)

  16. Edgars says:

    Thanks a lot, saved my day when have_posts() for some strange reason started to break.

    and to previous comments – for excerpt there is a the_excerpt() function, not post_excerpt.

  17. Adam says:

    thanks for sharing :)

  18. avinash gaud says:

    Hey thanks for sharing the tip

  19. admin says:

    @Robin, The example I added under the “Query X Number of Recent Posts” section of this post might help in your case.

  20. Robin says:

    I was wondering if you have a method of extracting a range of post id’s into an array to then use and display a range of posts (for example on a homepage). I don’t want to display the range the same way as its for a news site, so I’ve got a feature article, a medium one and a range of small ones. The problem i’ve got is that it keeps starting at the newest post, therefore repeating the newest one 3 times.

    This is what I’ve got for a query:

    query_posts(‘order=DESC&showposts=1′);
    if (have_posts()) : while (have_posts()) : the_post(); ?>

    //here i do stuff with the results
    <?php endwhile; endif;
    }

    The show posts is editable for a longer range of course, but out of this I'm wishing for a postID range so i can easily manage it as a single array of posts.

    Thanks in advance!

  21. admin says:

    There is a really easy way to get the custom field value of a particular WordPress post. Here is an example:

    <?php
    $key_1_values = get_post_meta(76, 'key_1');
    print_r($key_1_values);
    ?>

  22. sonofara says:

    very useful, but is there anyway to get post meta (custom fields)?

  23. web design says:

    good stuff, used one of your codes with an &offset, now I’m flying

  24. Unloari says:

    Actually like your websites particulars! Undoubtedly a wonderful offer of information that’s extraordinarily helpful. Carry on to carry publishing and i’m gonna proceed reading by the use of! Cheers.

  25. Auz says:

    Thanks for the snippet!

  26. Avenart says:

    Very helpful…Specially for displaying few specific posts. Thank you!

  27. Shaoib Ahmed says:

    thnaks alot buddy :) u rock

  28. O-o I see.
    I thinks that this command should work like normal excerpt in loop.
    I have another site that I use excerpt in home page loop and it works without adding any thing in excerpt field bellow posts!

    Is way to create same functionality in plugin or it is a lot of code?

    I’m not programmer! I now little PHP to rewrite some code for my custom templates or themes, but it’s not much. I always create custom theme for WordPress or custom templates for Joomla sites.
    So thank You that spend time to answer me!

  29. admin says:

    That should work as long as you have entered value in the Post excerpt field of the post. By default the post excerpt is empty. Did you add value in there when you edited the post?

  30. :-D it was exxerpt. It’s my mistake!

    Here is code:
    //$content = $queried_post->post_content;
    //$content = apply_filters(‘the_content’, $content);
    //$content = str_replace(‘]]>’, ‘]]>’, $content);
    //echo $content;

    $excerpt = $queried_post->post_excerpt;
    echo $excerpt;

    this commented one for CONTENT works well.
    But how to make this for EXCERPT work too.

    Should I apply some filter, like for content?

    Thank You in advice! Have a nice day!

  31. admin says:

    You probably should to echo “$excerpt” instead of “$content”?

  32. Thanks for sharing! That is exactly what I need.

    I could not show how the show excerpt instead of content.
    The code I have currently is:

    $excerpt = $queried_post->post_excerpt;
    echo $content;

    but it doesn’t work.
    Could you tell me where is wrong, please?
    How to change current code from tutorial?

    Thanks again!

  33. Shovan says:

    Amazing life saver.. Thanks a lot.
    To display in side bar I used PHP Code widget

    Thanks again

  34. admin says:

    @Sakura, what do you mean by another post table? Your WordPress posts are saved in wp_posts table by default.

  35. sakura says:

    hi, thanks for sharing this tip. I still have a question though,… I want to show all my post on my homepage but I want to get all the post from another post table on the same database. how do I do that? is it even possible?
    any response would be appreciated.
    thank you.

  36. stevan says:

    Hello, I am Brazilian and I found your blog on something that looked very much, thank you for
    tip and I will give to everyone. thanks

  37. admin says:

    @Naveed, try the following:

    $queried_post->guid

  38. Naveed Khan says:

    Thanks for the share of this post i would like to know how can we get permalink from $queried_post-> ?

    Answer will be very thanks full

  39. tech says:

    very nice hack now i resolved my problem, thanks!

  40. Rico says:

    Thanks for this great explanation and code!

  41. Tjen Penge says:

    Very nice article, just what I needed.
    Thanks !

  42. John Gamings says:

    Very neat trick. Some of these tips I just never would have even thought of

  43. Manish says:

    Thanks for nice post ,very very thanks

  44. Thanks for posting this! I spent about an hour looking through the poorly explained wordpress codex and despairing before I found this. Brilliant thanks!

  45. Very Good Tutorial I use

  46. Mehedi says:

    Thanks for this great tricks.

    Mehedi Hasan
    Web Designer & Developer

  47. admin says:

    When you retrieve the post you should be able to get everything associated with that post (this should include custom fields too)

  48. nele says:

    does this also work with the custom fields of the post? bcz the wordpress documentations doesnt seem to include this

  49. David says:

    Awesome, thanks for this. First site I went to and found the answer straight away. I thought it was going to be much more complicated than this.

  50. David Hobson says:

    Very nice, very helpful! I love just grabbing snippets of code without fully understanding php! Although knowing other languages helps.

    Have you considered indenting your code to make it more visibly intuitive? I think it would also be a good example for everyone out there! Thanks boss!

Speak Your Mind

*