[ad_1]
TL;DR: If you’re looking for an easy way to sort WordPress posts by date (be it descending or ascending) in the administration area without having users click on the Date column header, you can do so through the use of the pre_get_posts
filter that provides a reference to the instance WP_Query
running on the page.
For examples in code on how to do that, check out the rest of the article.
Sort WordPress Posts
This article is written such that it assumes your set up in class-based. This means that the set up for the filter is defined in a function such as init
and it invokes a public
function name on the class such as sort_articles_by_recent_time
.
Finally, it defines a priority of 10
and specifies the function will accept a single arguments (which is an instance of WP_Query
.
First, add the following filter:
add_action( 'pre_get_posts', [ $this, 'sort_articles_by_recent_time' ], 10, 1 );
Then add the following function:
public function sort_articles_by_recent_time( WP_Query $query ) {
global $pagenow;
if ( ! is_admin() || 'edit.php' !== $pagenow ) {
return;
}
$query->set( 'orderby', 'date' );
$query->set( 'order', 'desc' );
}
Here’s how it works:
- Note the first conditional checks if we’re not in the administration area or if we’re not on the
edit.php
page (which is the post listing page), we simply leave the functionality. This is a guard clause or an early return. - If we meet both of those criterias, then we’ll update the query so that it orders to posts by date in descending order. This means the most recent dates will always be listed at the top.
This does not account of post status (so if it’s a draft
or a post with the publish
status then it won’t matter). Further, this will prevent users from having to click on the Date column header to sort the results as needed if this is something you so desire in your solution.
References
[ad_2]
Source link