25% off ProSNIPC25OFF

Recently Updated Posts Shortcode

Shortcode [scseed_recently_updated] that lists posts ordered by last-modified date.

PHPby SnipCraft
php
<?php
// [scseed_recently_updated count="5" post_type="post" show_date="true"]
add_shortcode( 'scseed_recently_updated', 'scseed_recently_updated_shortcode' );
if ( ! function_exists( 'scseed_recently_updated_shortcode' ) ) {
    function scseed_recently_updated_shortcode( $atts ) {
        $atts = shortcode_atts( [
            'count'     => 5,
            'post_type' => 'post',
            'show_date' => true,
        ], $atts, 'scseed_recently_updated' );

        $query = new WP_Query( [
            'post_type'      => sanitize_key( $atts['post_type'] ),
            'posts_per_page' => absint( $atts['count'] ),
            'post_status'    => 'publish',
            'orderby'        => 'modified',
            'order'          => 'DESC',
            'no_found_rows'  => true,
        ] );

        if ( ! $query->have_posts() ) {
            return '';
        }

        $out = '<ul class="scseed-recently-updated">';
        while ( $query->have_posts() ) {
            $query->the_post();
            $out .= '<li class="scseed-recently-updated__item">';
            $out .= '<a href="' . esc_url( get_permalink() ) . '">'
                . esc_html( get_the_title() ) . '</a>';
            if ( filter_var( $atts['show_date'], FILTER_VALIDATE_BOOLEAN ) ) {
                $out .= ' <time class="scseed-modified-date" datetime="'
                    . esc_attr( get_the_modified_date( 'c' ) ) . '">'
                    . esc_html( get_the_modified_date() ) . '</time>';
            }
            $out .= '</li>';
        }
        $out .= '</ul>';
        wp_reset_postdata();
        return $out;
    }
}
#content#dates#display#posts#shortcode