Recent Posts Shortcode without a Plugin

WordPress has a stock Recent Posts widget which can be used in any widget area such as sidebars and footers. It displays a list of the titles of recent posts.

But what if you want to display recent posts in the main content area of a post or a page? What about the Featured Image and post Excerpt? You’ll have to install a plugin to do that, or you can add some code to your theme’s functions.php file and have more control over how the recent posts get displayed.

Here’s some basic code to create a shortcode for recent posts anywhere on pages. If your post has a Featured Image set it will get displayed as a thumbnail next to the post Excerpt. CSS classes can be added to style the HTML output.

Shortcode: [atconet_recent]

Add to your theme’s functions.php file:

// Creates shortcode that will display recent posts.
// Shortcode displays post title, excerpt with Read more link, and featured image.
function atconet_recent_posts($atts,$content = null) {
	$currentID = get_the_ID(); // get the ID of the current post or page
	$args = array(
	'post_type' => array('post'), // custom post types can be added: array('post', 'NAME'),
	'order' => 'DESC', // ASCending or DESCending 
	'posts_per_page' => '3', // how many posts to display
	'post__not_in' => array( $currentID) //  exclude the current page or post
	);

	$the_query = new WP_Query( $args );
		if ( $the_query->have_posts() ) :
				while ( $the_query->have_posts() ) : $the_query->the_post();

					$content .='<!-- recent post --><div>' .PHP_EOL;
					$content .='<h3><a href='.get_permalink().'>' .get_the_title() .'</a></h3>' .PHP_EOL;
					$content .='<p>';
					if ( has_post_thumbnail(get_the_ID()) ) {
						$content .='<a href='.get_permalink().'>' . get_the_post_thumbnail( $post->ID, 'thumbnail', array( 'class' => 'alignleft' ) ) . '</a>';
						}
					$content .= wp_trim_words( get_the_content(), 55, '...' ); // # words in excerpt
					$content .='<a href="'.get_permalink().'">Read more</a></p>' .PHP_EOL;
					$content .='</div><!-- #recent post -->'. PHP_EOL;

				endwhile;

	wp_reset_postdata();

	return $content;
	endif;
}

Two Recent Posts

Force Category Selection Plugin

Sometimes, our enthusiasm gets the best of us and we forget to select a Category when publishing a post, and when viewing the archive page or widgets the post is not displayed or listed. Then we may wonder what happened to the post [...]

Read more...

Automatic Meta Description Tags Using Excerpts

The default installation of WordPress does not contain the description and keywords meta tag data. Meta tags can be added manually, through changes to the Theme template files, WordPress Plugins or by adding code to your theme's functions.php file. What Are Meta Tags? [...]

Read more...