Categories
Functions

How to create a short code to display recent posts

You may want to display most recent posts of your website in your WordPress website post or page. You can achieve that creating a custom WordPress shortcode. Let me first explain what is a WordPress shortcode and how it works.

What is a WordPress shortcode?

WordPress Shortcode is a feature defined in WordPress core that allows you to define a code programmatically for any dynamic content. You can then use the code inside WordPress post editor, page editor, custom post editor, or WordPress widget. You have to use the defined code wherever you want to display the dynamic content, and you can see the new dynamic content in place of the code in front-end. WordPress shortcode is one of the most important features in WordPress that makes it very easy to use.

add_shortcode function

To define a custom WordPress shortcode, you have to use a WordPress core function called add_shortcode. It accepts two parameters, the tag or code name in string format and a callback function name. The call back function should have a definition of the dynamic content that you want to return in place of the shortcode. Remember, the call back function should always return the dynamic content that you want to display.

Here is an example of creating a Hello World shortcode.

<?php
add_shortcode( 'hello_world', 'wptips_helloworld' );
function wptips_helloworld( $atts ) {
    return "Hello World";
}
?>

Once you have defined the above shortcode, you can call the shortcode by using the code [hello_world] . It will show as “Hello World” , in frontend.

Now, Lets create a custom shortcode to display 5 recent posts.

<?php
function wptips_recent_posts_shortcode($atts){
$query = new WP_Query(array( 'orderby' => 'date', 'posts_per_page' => '5') );
$list = '<ul class="recent-posts">';
  while($query->have_posts()) : $query->the_post();
		$list .= '<li>' . get_the_date() . '<a href="' . get_permalink() . '">' . get_the_title() . '</a>' . '<br />' . get_the_excerpt() . '</li>';
  endwhile;
wp_reset_query();
$list .= '</ul>';
  return $list;
}
add_shortcode('recent-posts', 'wptips_recent_posts_shortcode');
?>

By Murali Kumar

I am a Full Stack Web Developer with over 12 years of experience. I love WordPress & WooCommerce.

If you need help of a WordPress developer for your website, get in touch now!.

Follow me on Twitter : @geekz

Leave a Reply

Your email address will not be published. Required fields are marked *