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
*/