这个WP_Query 类可以匹配ID和搜索词。一个想法是使用pre_get_posts
用于检测搜索词是否为数字的操作,如果是,则将查询设置为使用附件,同时将搜索作为ID传递。
function wpse223307_allow_search_by_attachment_id( $query ) {
//Only alter the query if we are in a search screen,...
if( ! is_search() ) :
return;
endif;
//...the search term has been set...
if( ! isset( $query->query_vars[\'s\'] ) ) :
return;
endif;
$search_term = $query->query_vars[\'s\'];
//...and the search term is a number
if( ! is_numeric( $search_term ) ) :
return;
endif;
//Set the post type and post status to work with attachments (assuming you want to exclude other post types in numeric searches)
$query->set( \'post_type\', array( \'attachment\' ) );
$query->set( \'post_status\', array( \'inherit\' ) );
//Match the search term with the attachment\'s ID and remove it from the query
$query->set( \'p\', $search_term );
$query->set( \'s\', \'\' );
}
add_action( \'pre_get_posts\', \'wpse223307_allow_search_by_attachment_id\');