If you maintain specific posts on your blog which are regularly updated with new information, it’s best to sort the posts on your homepage with the recently updated posts on your site to get more visibility to the updated content.

To order homepage posts by date modified on your WordPress site, paste the code below to your theme’s functions.php or your functionality plugin.

function order_post_modifed( $query )
{
if ( $query->is_main_query() && ( $query->is_home() || $query->is_search() || $query->is_archive() ) )
{
$query->set( 'orderby', 'modified' );
$query->set( 'order', 'desc' );
}
}
add_action( 'pre_get_posts', 'order_post_modifed' );

Once the code is added, clear the cache of your WordPress site (if you use a caching system) to see the recently updated posts on your site’s homepage.

If you’d like sort posts by date modified in the WordPress admin area as well, remove the following piece of code from the code above.

&& ( $query->is_home() || $query->is_search() || $query->is_archive() )

The altered code for displaying posts by date modified in the backend as well would look like this:

function order_post_modifed( $query )
{
if ( $query->is_main_query() )
{
$query->set( 'orderby', 'modified' );
$query->set( 'order', 'desc' );
}
}
add_action( 'pre_get_posts', 'order_post_modifed' );

Note: The code above will work for most WordPress themes but not all. Please check with your theme’s developer to ensure compatibility.

Author

Leave a Reply