search
HomeCMS TutorialWordPressCustomized WordPress Administration Filters

This article explains how to use WordPress filters to customize the post administration screen. We'll cover WordPress's built-in filters and show you how to create custom filters to enhance functionality.

Key Concepts

  • WordPress provides default filters on the post administration screen to display posts based on specific criteria. These filters are extensible.
  • New filters are added using the restrict_manage_posts and pre_get_posts hooks. These allow filtering posts by various criteria.
  • Custom filters for post formats and authors can be created by adding code to your theme's functions.php file (or a plugin).
  • The pre_get_posts filter modifies the database query, controlling which posts are displayed.
  • Custom filters improve user experience, add functionality, and maintain clean code.

Filtering Posts: The Basics

WordPress offers default filters on the post administration screen (like date filtering, shown below). Themes and plugins can add more. These filters narrow down the post list based on specified criteria.

Customized WordPress Administration Filters

Creating Custom Filters

While WordPress offers built-in filters, you often need custom ones for better user experience. Two hooks are key:

  • restrict_manage_posts: Adds new filter controls to the admin screen's top.
  • pre_get_posts: Modifies the query before it runs, filtering the displayed posts.

Example: Filtering by Author and Post Format

Let's create filters for post authors and formats. Imagine a website where posts have manually assigned formats and authors. The default admin screen can be overwhelming. We'll add dropdown menus for easier filtering.

Adding Dropdown Menus (restrict_manage_posts)

Add the following code to your theme's functions.php file (or a plugin):

Filter by Author:

function add_author_filter() {
    global $post_type;
    if ($post_type == 'post') {
        $user_args = array(
            'show_option_all' => 'All Authors',
            'orderby' => 'display_name',
            'order' => 'ASC',
            'name' => 'author_filter',
            'who' => 'authors',
            'include_selected' => true
        );
        if (isset($_GET['author_filter'])) {
            $user_args['selected'] = (int) sanitize_text_field($_GET['author_filter']);
        }
        wp_dropdown_users($user_args);
    }
}
add_action('restrict_manage_posts', 'add_author_filter');

Filter by Post Format:

function add_post_format_filter() {
    global $post_type;
    if ($post_type == 'post') {
        $post_formats_args = array(
            'show_option_all' => 'All Formats',
            'orderby' => 'NAME',
            'order' => 'ASC',
            'name' => 'post_format_filter',
            'taxonomy' => 'post_format'
        );
        if (isset($_GET['post_format_filter'])) {
            $post_formats_args['selected'] = sanitize_text_field($_GET['post_format_filter']);
        }
        wp_dropdown_categories($post_formats_args);
    }
}
add_action('restrict_manage_posts', 'add_post_format_filter');

This adds two dropdowns to the post list screen.

Customized WordPress Administration Filters

Filtering the Post List (pre_get_posts)

Now, let's make the dropdowns functional:

Filtering by Author:

function filter_posts_by_author($query) {
    global $post_type, $pagenow;
    if ($pagenow == 'edit.php' && $post_type == 'post' && isset($_GET['author_filter'])) {
        $author_id = sanitize_text_field($_GET['author_filter']);
        if ($author_id != 0) {
            $query->set('author', $author_id);
        }
    }
}
add_action('pre_get_posts', 'filter_posts_by_author');

Filtering by Post Format:

function filter_posts_by_format($query) {
    global $post_type, $pagenow;
    if ($pagenow == 'edit.php' && $post_type == 'post' && isset($_GET['post_format_filter'])) {
        $post_format = sanitize_text_field($_GET['post_format_filter']);
        if ($post_format != 0) {
            $query->set('post_format', $post_format);
        }
    }
}
add_action('pre_get_posts', 'filter_posts_by_format');

These functions modify the query to only include posts matching the selected author or post format.

Customized WordPress Administration Filters

Conclusion

This enhanced your WordPress admin with custom filters. You can adapt this to filter by other post attributes (refer to the WordPress Query class documentation). Remember to always sanitize user inputs to prevent security vulnerabilities.

The above is the detailed content of Customized WordPress Administration Filters. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Does WordPress require coding knowledge to use as a CMS?Does WordPress require coding knowledge to use as a CMS?Apr 30, 2025 am 12:03 AM

You don't need programming knowledge to use WordPress, but mastering programming can improve the experience. 1) Use CSS and HTML to adjust the theme style. 2) PHP knowledge can edit topic files and add functions. 3) Custom plug-ins and meta tags can optimize SEO. 4) Pay attention to backup and use of sub-topics to prevent update issues.

What are the security considerations when using WordPress?What are the security considerations when using WordPress?Apr 29, 2025 am 12:01 AM

TosecureaWordPresssite,followthesesteps:1)RegularlyupdateWordPresscore,themes,andpluginstopatchvulnerabilities.2)Usestrong,uniquepasswordsandenabletwo-factorauthentication.3)OptformanagedWordPresshostingorsecuresharedhostingwithawebapplicationfirewal

How does WordPress compare to other website builders?How does WordPress compare to other website builders?Apr 28, 2025 am 12:04 AM

WordPressexcelsoverotherwebsitebuildersduetoitsflexibility,scalability,andopen-sourcenature.1)It'saversatileCMSwithextensivecustomizationoptionsviathemesandplugins.2)Itslearningcurveissteeperbutofferspowerfulcontroloncemastered.3)Performancecanbeopti

5  WordPress Plugins for Developers To Use in 20255 WordPress Plugins for Developers To Use in 2025Apr 27, 2025 am 08:25 AM

Seven Must-Have WordPress Plugins for 2025 Website Development Building a top-tier WordPress website in 2025 demands speed, responsiveness, and scalability. Achieving this efficiently often hinges on strategic plugin selection. This article highlig

What would you use WordPress for?What would you use WordPress for?Apr 27, 2025 am 12:14 AM

WordPresscanbeusedforvariouspurposesbeyondblogging.1)E-commerce:WithWooCommerce,itcanbecomeafullonlinestore.2)Membershipsites:PluginslikeMemberPressenableexclusivecontentareas.3)Portfoliosites:ThemeslikeAstraallowstunninglayouts.Ensuretomanageplugins

Is WordPress good for creating a portfolio website?Is WordPress good for creating a portfolio website?Apr 26, 2025 am 12:05 AM

Yes,WordPressisexcellentforcreatingaportfoliowebsite.1)Itoffersnumerousportfolio-specificthemeslike'Astra'foreasycustomization.2)Pluginssuchas'Elementor'enableintuitivedesign,thoughtoomanycanslowthesite.3)SEOisenhancedwithtoolslike'YoastSEO',boosting

What are the advantages of using WordPress over coding a website from scratch?What are the advantages of using WordPress over coding a website from scratch?Apr 25, 2025 am 12:16 AM

WordPressisadvantageousovercodingawebsitefromscratchdueto:1)easeofuseandfasterdevelopment,2)flexibilityandscalability,3)strongcommunitysupport,4)built-inSEOandmarketingtools,5)cost-effectiveness,and6)regularsecurityupdates.Thesefeaturesallowforquicke

What makes WordPress a Content Management System?What makes WordPress a Content Management System?Apr 24, 2025 pm 05:25 PM

WordPressisaCMSduetoitseaseofuse,customization,usermanagement,SEO,andcommunitysupport.1)Itsimplifiescontentmanagementwithanintuitiveinterface.2)Offersextensivecustomizationthroughthemesandplugins.3)Providesrobustuserrolesandpermissions.4)EnhancesSEOa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools