WordPress has a tool called a widget that can show your most recent posts in sidebars or widget areas on your website. Many WordPress themes also have a way to show recent posts, so you can display your latest articles in different spots on your site. This is handy for showing recent posts in various places in your theme. But, here’s the issue: these methods won’t work if you want to show recent posts inside your actual articles, pages, or custom post types. For that, we can use something called a shortcode.
Shortcode to the rescue
If you want to show a list of related posts inside the WordPress post editor (like the editor where you write your posts), you can do it using the default WordPress widget or a plugin. However, that might be more than what you need depending on your website’s plans and objectives. Instead, you can achieve this by adding a straightforward piece of code to your theme’s ‘functions.php’ file.
function diwakar_recent_posts_shortcode($atts, $content = null) { global $post; extract(shortcode_atts(array( 'cat' => '', 'num' => '5', 'order' => 'DESC', 'orderby' => 'post_date', ), $atts)); $args = array( 'cat' => $cat, 'posts_per_page' => $num, 'order' => $order, 'orderby' => $orderby, ); $output = ''; $posts = get_posts($args); foreach($posts as $post) { setup_postdata($post); $output .= '<li><a href="'. get_the_permalink() .'">'. get_the_title() .'</a></li>'; } wp_reset_postdata(); return '<ul>'. $output .'</ul>'; } add_shortcode('recent_posts', 'diwakar_recent_posts_shortcode');
This code makes a shortcut that can grab specific posts from your WordPress site’s database and show them on your posts or pages. It’s as easy as counting to three! You don’t need to change anything; you can use this ‘recent posts’ shortcut in any WordPress theme. Or, if you prefer, you can add this code to your site through a simple plugin.
Usage
To use the ‘recent-posts’ shortcut, just put the following code into any WordPress post or page.
[recent_posts num=”5″ cat=”7″]
That will show a list of five posts from category ID 7. You can change the settings to fit your needs. The shortcode also works with a couple of other options like ‘order’ and ‘orderby’:
[recent_posts num=”10″ cat=”” order=”asc” orderby=”rand”]
Now, the list will show 10 posts from any category, arranged randomly, and displayed in ascending order.
Code explanation
This ‘recent-posts’ trick uses the WP ‘add_shortcode()’ function along with the ‘get_posts()’ template tag. Here’s how it works: we set up all the details, use ‘get_posts()’ to fetch data from the database, and then show the results in a list format on the page. And, of course, we connect everything to WordPress using the Shortcode API. So, it’s pretty standard stuff. What’s cool is that ‘get_posts()’ uses the same parameters as ‘WP_Query,’ so you can do a lot more to customize and request very specific groups of posts. If you want more ideas, you can check out the WP_Query documentation.
Related Articles
Leave a Reply