WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Could someone help me write a custom shortcode to simply display the latest post anywhere in Wordpress? I've seen a lot of ways how to do this in pure PHP in a custom page template, but if I try to convert it, I always get problems (double display) or completely nothing. It should be just one post (not page) of any kind at all, as long as it's the most recent one.

I just need it like this:

<a href="permalink" class="button">Read more</a>

I've also looked for some plugins, but that's also problematic. They break all shortcode functionality or they just display a list...

Can anyone help me out and score some points? I would surely appreciate it.

share|improve this question
up vote 5 down vote accepted

In functions.php file :

 function my_recent_post()
      global $post;

      $html = "";

      $my_query = new WP_Query( array(
           'post_type' => 'post',
           'posts_per_page' => 1

      if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post();

           $html .= "<h2>" . get_the_title() . "</h2>";
           $html .= "<p>" . get_the_excerpt() . "</p>";
           $html .= "<a href=\"" . get_permalink() . "\" class=\"button\">Read more</a>";

      endwhile; endif;

      return $html;
 add_shortcode( 'recent', 'my_recent_post' );

And the shortcode would be [recent].

Code is untested, but should look something like that.

share|improve this answer
the general code is fine - however, it is not recommended to use query_posts() in a secondary loop - try to work with WP_Query() or get_posts() – Michael Feb 1 '12 at 18:22
@Michael Yes you're right, I updated my example in consequence. – Shane Feb 1 '12 at 18:26
Even better to use get_post when its just one post – Bainternet Feb 1 '12 at 18:42
@Bainternet How would you go about getting the latest post ID? Wouldn't you need a query to obtain that before using get_post, or is the ID stored elsewhere? – Shane Feb 1 '12 at 19:01
I would add a reset query after the loop, that way you guarantee it won't break any other code into the page. As far as I know you, you can just add the_ID, and I will return the post id, since you are showing only one post, you are getting only the last id, what would you need it for? – andresmijares25 Feb 1 '12 at 21:10

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.