Day: October 14, 2021

Sort posts by last updated date in WordPress

Sort posts by last updated date in WordPress

Solution

In recent post list, the date of sorting is based on published date, so the updates will never be shown. To change this behavior, following code can be appended into functions.php to archive the sorting by last updated date.

function lmt_orderby_modified_posts( $query ) {
    if( $query->is_main_query() && !is_admin() ) {
        if ( $query->is_home() || $query->is_category() || $query->is_tag() ) {
            $query->set( 'orderby', 'modified' );
            $query->set( 'order', 'desc' );
        }
    }
}
add_action( 'pre_get_posts', 'lmt_orderby_modified_posts' );

Issue

There is an issue after changed sorting and modified post day, the archives will still be under published date, which can be comfusing.

If there is a way change permalink structure based on last updated date, then could be much simple.

References

Sort posts by modified date in the frontend
Using Permalinks
Simple Guide to Changing Your Permalinks Without Breaking Your WordPress Site

Last updated date in WordPress

Last updated date in WordPress

There are a few methods to display last updated in WordPress

Change post date to last updated date

But default, post date is published date, if like to change it to last updated date, add additional CSS as below.

/* for post modified */
.entry-date.published { display: none; }
.updated:not(.published) { display: inline-block; }

/* for post that never been modified, theme uses .updated */
.entry-date.published.updated { display: inline-block; }

Change functions.php

function my_last_updated_date( $content ) {
    $u_time = get_the_time('U');
    $u_modified_time = get_the_modified_time('U');

    if ($u_modified_time >= $u_time + 86400) {
        $updated_date = get_the_modified_time('F jS, Y');
        $updated_time = get_the_modified_time('h:i a');
        $custom_content .= '<p class="last-updated entry-meta">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';
    }

    $custom_content .= $content;
    return $custom_content;
}
add_filter( 'the_content', 'my_last_updated_date' );

Change template-tags.php

This is the PHP way to modify the code to display dates.

References

How to replace published date?