>本文說明瞭如何使用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中文網其他相關文章!