How to automatically sort the order of a custom post type in the WordPress admin area

To automatically sort a custom post type by date in the WordPress admin, you can use the pre_get_posts action hook. Here’s a function that you can add to your theme’s functions.php file or a custom plugin:





Explanation:

  • is_admin(): Ensures that the function only runs in the admin area.
  • $query->is_main_query(): Ensures that we are modifying the main query, not any secondary queries.
  • $query->get('post_type') === 'your_custom_post_type': This condition ensures that the sorting is applied only to the specific custom post type you want to target. Replace 'your_custom_post_type' with the actual slug of your custom post type.
  • $query->set( 'orderby', 'date' ): Orders the posts by the date field.
  • $query->set( 'order', 'DESC' ): Sorts the posts in descending order (most recent posts first).

This function will automatically sort the posts of the specified custom post type by date in the WordPress admin area.

Recent Posts