How to search post by ID in wp-admin

Solution 1

Here’s a solution that uses pre_get_posts action to override the original search query and search by post ID instead. This is the approach that I would generally recommend.

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

Here’s an alternative solution that uses the posts_search filter to modify the SQL directly when a search is made in the admin area using a numeric value.

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

Either of these solutions can be easily turned into a plugin by saving the snippet to a file named admin-search-by-post-id.php in a folder named admin-search-by-post-id (for example).
See the Developer Handbook on plugin creation for details.

Example plugin header:

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

Leave a Comment