0

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:

<h2>Title</h2>
<p>Excerpt...</p>
<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.

1 Answer 1

6

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.

7
  • 2
    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
    Commented Feb 1, 2012 at 18:22
  • 3
    @Michael Yes you're right, I updated my example in consequence.
    – Shane
    Commented Feb 1, 2012 at 18:26
  • 1
    Even better to use get_post when its just one post
    – Bainternet
    Commented Feb 1, 2012 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
    Commented Feb 1, 2012 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? Commented Feb 1, 2012 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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