Shortcode for Listing the Recent Posts or CPTs
To list the recent posts or posts of a custom post type (CPT), you can add this code to your website:
function wpkb_shortcode_list_recent_posts($attributes)
{
// Define defaults for attributes
$attributes = shortcode_atts( array(
'post_type' => 'post',
'number_of_posts' => '5',
), $attributes );
// WP_Query arguments
$args = array(
'post_type' => array( $attributes['post_type'] ),
'posts_per_page' => $attributes['number_of_posts'],
'order' => 'DESC',
'orderby' => 'date',
);
// Initialize output
$output = '<ul>';
// Get posts
$posts = get_posts( $args );
// Add posts to list
foreach ( $posts as $post ) {
setup_postdata($post);
$output .= '<li><a href="'. get_the_permalink($post->ID) .'">'. get_the_title($post->ID) .'</a></li>';
}
// Add info if there are no matching posts
if (!$posts) {
$output .= '<li>No posts found</li>';
}
// Reset postdata
wp_reset_postdata();
// Close output tag
$output .= '</ul>';
// Return output
return $output;
}
add_shortcode('recent_posts', 'wpkb_shortcode_list_recent_posts');
After adding the code above, you may use the shortcode [[recent_posts]]. By default, the shortcode shows the recent 5 posts of type post. If you want to show the latest 10 posts of type kb_entry instead, you have to use the shortcode [[recent_posts post_type=“kb_entry” number_of_posts=“10”]].
Related Posts
- Shortcode Showing the Latest Posts Using Timber
- Fix "Failed to get metadata: Local: Broker transport failure" When Updating Sentry
- Minimal Template for Relevanssi Related Posts
- Configure WordPress Backend Search to Search Titles Only
- Manage MySQL Databases and Users from the Command Line
- Shortcode to List (Custom) Taxonomy Terms