Wordpress: Custom Shortcode for Recent Posts
Enhance your WordPress content with dynamic lists of recent posts using this custom shortcode snippet, making it easy to insert anywhere on your site.
Shortcodes in WordPress provide a powerful way to add dynamic content to posts or pages. This snippet creates a custom shortcode that displays a list of recent posts, which can be easily added to any part of the site via the editor.
The add_shortcode
function is used to define a new shortcode [recent_posts]
that generates an HTML list of the latest posts. Users can customize the number of posts displayed by passing a parameter to the shortcode.
This example includes details on how to query the posts using WP_Query
and how to loop through the results to build the output list. It also covers how to make the output customizable via attributes in the shortcode, like the number of posts to display.
Additional features such as including post thumbnails or excerpts in the output are discussed, along with how to handle empty results or errors gracefully.
The snippet also provides tips on styling the output of the shortcode using CSS, ensuring that it blends seamlessly with the site's design.
Snippet Code
Version Compatibility
This code is compatible with WordPress 2.5 and later, where shortcodes were introduced.
Required PHP Version
PHP 5.6 or higher
Wordpress Core Functions Used
Use Cases
- content display
- shortcode usage
- dynamic content insertion