>本文说明了如何使用WordPress过滤器自定义邮政管理屏幕。 我们将介绍WordPress的内置过滤器,并向您展示如何创建自定义过滤器以增强功能。
关键概念restrict_manage_posts
pre_get_posts
>可以通过将代码添加到主题的functions.php
pre_get_posts
创建自定义过滤器
> WordPress提供内置过滤器时,您通常需要自定义的过滤器才能获得更好的用户体验。 两个钩子是关键:
:将新的过滤器控件添加到管理员屏幕的顶部。
restrict_manage_posts
>示例:作者和邮政格式过滤pre_get_posts
>
>文件(或插件):
restrict_manage_posts
functions.php
<code class="language-php">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');</code>
<code class="language-php">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');</code>)
现在,让我们使下拉列表功能:
>作者过滤:
pre_get_posts
>通过邮政格式过滤:这些函数将查询修改为仅包含匹配所选作者或邮政格式的帖子。
<code class="language-php">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');</code>
这通过自定义过滤器增强了您的WordPress管理员。 您可以通过其他帖子属性(请参阅WordPress查询类文档)进行过滤。 请记住要始终对用户输入进行消毒以防止安全漏洞。
>以上是定制的WordPress管理过滤器的详细内容。更多信息请关注PHP中文网其他相关文章!