如何在wp-admin中按ID搜索帖子

时间:2018-03-12 作者:Nobody

当我转到管理区域中的帖子列表时,我只能按帖子标题或内容进行搜索。

我想添加一个按帖子或页面id搜索的功能,使编辑更容易找到他们正在寻找的帖子。

我需要在插件文件夹中实现它。有什么想法吗?我不知道现在该从哪里开始。谢谢大家!

enter image description here

1 个回复
SO网友:Dave Romsey

Solution 1

这里有一个解决方案pre_get_posts 覆盖原始搜索查询并改为按帖子ID搜索的操作。这是我通常建议的方法。

/**
 * Allows posts to be searched by ID in the admin area.
 * 
 * @param WP_Query $query The WP_Query instance (passed by reference).
 */
add_action( \'pre_get_posts\',\'wpse_admin_search_include_ids\' );
function wpse_admin_search_include_ids( $query ) {
    // Bail if we are not in the admin area
    if ( ! is_admin() ) {
        return;
    }

    // Bail if this is not the search query.
    if ( ! $query->is_main_query() && ! $query->is_search() ) {
        return;
    }   

    // Get the value that is being searched.
    $search_string = get_query_var( \'s\' );

    // Bail if the search string is not an integer.
    if ( ! filter_var( $search_string, FILTER_VALIDATE_INT ) ) {
        return;
    }

    // Set WP Query\'s p value to the searched post ID.
    $query->set( \'p\', intval( $search_string ) );

    // Reset the search value to prevent standard search from being used.
    $query->set( \'s\', \'\' );
}

Solution 2

这里有一个替代解决方案,它使用posts_search 当在管理区域中使用数值进行搜索时,可通过过滤器直接修改SQL。

/**
 * Modify search SQL enabling searching by post ID.
 *
 * @param string   $search Search SQL for WHERE clause.
 * @param WP_Query $wp_query   The current WP_Query object.
 */
add_filter( \'posts_search\', \'wpse_posts_search_post_id\', 10, 2 );
function wpse_posts_search_post_id( $search, $wp_query ) {
    // Bail if we are not in the admin area
    if ( ! is_admin() ) {
        return $search;
    }

    // Bail if this is not the search query.
    if ( ! $wp_query->is_main_query() && ! $wp_query->is_search() ) {
        return $search;
    }   

    // Get the value that is being searched.
    $search_string = get_query_var( \'s\' );

    // Bail if the search string is not an integer.
    if ( ! filter_var( $search_string, FILTER_VALIDATE_INT ) ) {
        return $search;
    }

    // This appears to be a search using a post ID.
    // Return modified posts_search clause.
    return "AND wp_posts.ID = \'" . intval( $search_string )  . "\'";
}

Using this code

通过将代码片段保存到名为admin-search-by-post-id.php 在名为admin-search-by-post-id (例如)。请参见Developer Handbook on plugin creation 有关详细信息。

插件标题示例:

<?php
/*
Plugin Name:  Admin Search by Post ID
Plugin URI:   
Description:  Allows posts to be searched using IDs in the admin area.
Version:      0.0.1
Author:       
Author URI:   
License:      GPL2
License URI:  https://www.gnu.org/licenses/gpl-2.0.html
Text Domain:  your_text_domain
Domain Path:  /languages
*/

结束