Recent Posts Shortcode
Adds a [recent_posts] shortcode that lists your latest posts anywhere, optionally from one category and with dates.
Opens WPIDE on
Code
add_shortcode( 'recent_posts', function ( $atts ) {
$atts = shortcode_atts( array(
'number' => 5,
'category' => '',
'show_date' => 'no',
), $atts, 'recent_posts' );
$args = array(
'numberposts' => min( 50, max( 1, absint( $atts['number'] ) ) ),
'post_status' => 'publish',
'ignore_sticky_posts' => true,
'no_found_rows' => true,
'post__not_in' => array( get_the_ID() ),
);
if ( '' !== $atts['category'] ) {
$args['category_name'] = sanitize_title( $atts['category'] );
}
$posts = get_posts( $args );
if ( ! $posts ) {
return '';
}
$html = '<ul class="wpide-recent-posts">';
foreach ( $posts as $item ) {
$date = 'yes' === $atts['show_date'] ? ' <time datetime="' . esc_attr( get_the_date( 'c', $item ) ) . '">' . esc_html( get_the_date( '', $item ) ) . '</time>' : '';
$html .= '<li><a href="' . esc_url( get_permalink( $item ) ) . '">' . esc_html( get_the_title( $item ) ) . '</a>' . $date . '</li>';
}
return $html . '</ul>';
} );
Notes
Example: [recent_posts number="5" category="news" show_date="yes"].
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.