Recently Updated Posts Shortcode
Adds a [recently_updated] shortcode that lists the posts most recently revised, with the date they were updated, to show readers that older guides are being kept fresh.
Opens WPIDE on
Code
add_action( 'init', function () {
add_shortcode( 'recently_updated', function ( $atts ) {
$atts = shortcode_atts( array( 'count' => 5, 'post_type' => 'post' ), $atts, 'recently_updated' );
$cache_key = 'wpide_recent_upd_' . md5( wp_json_encode( $atts ) . get_option( 'wpide_recent_upd_ver', '1' ) );
$html = get_transient( $cache_key );
if ( false !== $html ) {
return $html;
}
global $wpdb;
$types = array_filter( array_map( 'sanitize_key', explode( ',', $atts['post_type'] ) ) );
$in = implode( ',', array_fill( 0, count( $types ), '%s' ) );
$ids = $wpdb->get_col( $wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type IN ($in) AND post_password = ''
AND post_modified_gmt > DATE_ADD(post_date_gmt, INTERVAL 1 DAY) ORDER BY post_modified_gmt DESC LIMIT %d",
array_merge( $types, array( max( 1, min( 20, (int) $atts['count'] ) ) ) )
) );
$html = '';
if ( $ids ) {
_prime_post_caches( $ids, false, false );
$html = '<ul class="wpide-recently-updated">';
foreach ( $ids as $id ) {
$html .= sprintf(
'<li><a href="%s">%s</a> <small>updated <time datetime="%s">%s</time></small></li>',
esc_url( get_permalink( $id ) ),
esc_html( get_the_title( $id ) ),
esc_attr( get_post_modified_time( 'c', true, $id ) ),
esc_html( get_the_modified_date( '', $id ) )
);
}
$html .= '</ul>';
}
set_transient( $cache_key, $html, HOUR_IN_SECONDS );
return $html;
} );
} );
// A new version number makes every cached list stale at once.
add_action( 'save_post', function ( $post_id, $post ) {
if ( 'revision' !== $post->post_type && 'auto-draft' !== $post->post_status ) {
update_option( 'wpide_recent_upd_ver', (string) time(), false );
}
}, 10, 2 );
Notes
Example [recently_updated count="5" post_type="post,page"]; posts edited within a day of publishing are skipped so new posts do not crowd the list.
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.