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.

More Articles
  • A tranquil scene of Canadian Geese flying in formation against a clear sky in Decatur, Alabama.

    How to Migrate a Magento Commerce Website to WordPress and WooCommerce: A Step-by-Step Guide

    If your Magento Commerce website has become expensive to maintain, difficult to customize, or more complex than your business needs, you’re not alone. Many businesses are making the move to WordPress and WooCommerce to reduce costs, simplify website management, and gain greater flexibility for content marketing and SEO. A successful migration requires more than simply…

  • Close-up of a bright yellow disabled symbol on textured asphalt, indicating accessibility.

    Website Accessibility Review Workflow

    Version: 1.0Standard: WCAG 2.2 AAAudience: Web Developers, QA Testers, UI Designers Phase 1 – Automated Accessibility Scan Goal: Find common accessibility issues before manual testing. Checklist ☐ Run an accessibility scan on every page template. ☐ Review all reported errors. ☐ Fix high-impact issues first: ☐ Re-run scan until no critical issues remain. Recommended Tools…

  • accessible parking spot comparing ADA rules to WCAG rules

    What Is the Industry Standard Website Scanner for WCAG Compliance?

    If you’re trying to make your website accessible, one of the first questions you’ll probably ask is: “What’s the industry-standard scanner for WCAG compliance?” The short answer is: there isn’t just one. While several excellent accessibility scanners exist, no automated tool can certify that a website is fully compliant with the Web Content Accessibility Guidelines…