Sorting Custom Post Type Posts from Admin Panel

By default custom post type (CPT) posts in WP admin panel gets sorted alphabetically, at least that was my experience. Now, this could be bit problematic or may be should I say “not so efficient” for many reasons.

For the sake of arguments, let’s assume that you have a custom post type called “books” and you wrote well over hundreds of reviews. Since WP will sort them alphabetically, chances are pretty high that you won’t see your latest post at the top (specially if your post title starts with anything but “a”). Most probably your latest post is within the piles of posts.

One way to resolve this issue could be, sorting your posts by their published date, how would you do that? Here is the solution.

function cpt_orderby_date($query){
   if (is_admin() && $query->is_post_type_archive('books')) {
   return; } }

All you have to do now is simply copy and paste the snippet on your theme’s functions.php page. Also change the name of your custom post type within if statement. It should sort all of your custom post type (books) posts by their published date. You can find additional order and orderby parameters value from the WordPress codex page.

Note: If you take a closer look, you can see that I hooked our main function with pre_get_posts action. It is both useful and potentially dangerous as it can affect the query made on both the front-end and back-end of WordPress. That’s just one reason why I used if statement to check if it is_admin page and also the post archive page for books post type using is_post_type_archive function.

Today In History



Leave a Reply

Note: Convet HTML, PHP, JavaScripts from HTMLify, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.