
In order to meet the requirement that the Home page include the three latest Blog posts, a WordPress shortcode was built into the Functions file of the theme. Use the shortcode [ latestposts ] (remove spaces) to render the three most recent posts in any page. This feature is being introduced as part of the “Bootstrap Pro” WordPress theme.
This code can be repurposed to display recent posts from specific categories, change the number of posts shown, and change the structure of the rendered component. The full code snippet is below. The original code was taken from Anna Fitzgerald’s “How to Display Recent Posts on Any WordPress Page”
Upcoming development items:
- Build up the preview components for the Latest Posts shortcode to match exactly the ones on the Blog
- Don’t render the H1 title in the Home page, as it will be manually included in the WordPress editor
- Render the H1 title in the Blog
Find the full PHP code for the Latest Posts shortcode below. Note that category_name can be edited with the category slug, and posts_per_page with a number. If you create a new shortcode, remember to update the add_shortcode function with your new shortcode name.
/**
* Latest Posts Shortcode Component
*
* V1 added to Bootstrap Pro theme 14 June 2023
*
*/
function wpcat_latestposts() {
// the query
$the_query = new WP_Query( array( 'category_name' => '', 'posts_per_page' => 3 ) );
// The Loop
if ( $the_query->have_posts() ) {
$string .= '<ul class="latestposts widget_recent_entries">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
if ( has_post_thumbnail() ) {
$string .= '<li>';
$string .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 50, 50) ) . get_the_title() .'</a></li>';
} else {
// if no featured image is found
$string .= '<li><a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() .'</a></li>';
}
}
} else {
// no posts found
}
$string .= '</ul>';
return $string;
/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('latestposts', 'wpcat_latestposts');
// Enable shortcodes in text widgets
add_filter('widget_text', 'do_shortcode');