Search posts by ID in admin

Not sure i understand why you’d want to query by ID, but that said it’s possible in a hacky kind of way(i like this method because it’s simple).

add_action( 'parse_request', 'idsearch' );
function idsearch( $wp ) {
    global $pagenow;

    // If it's not the post listing return
    if( 'edit.php' != $pagenow )
        return;

    // If it's not a search return
    if( !isset( $wp->query_vars['s'] ) )
        return;

    // If it's a search but there's no prefix, return
    if( '#' != substr( $wp->query_vars['s'], 0, 1 ) )
        return;

    // Validate the numeric value
    $id = absint( substr( $wp->query_vars['s'], 1 ) );
    if( !$id )
        return; // Return if no ID, absint returns 0 for invalid values

    // If we reach here, all criteria is fulfilled, unset search and select by ID instead
    unset( $wp->query_vars['s'] );
    $wp->query_vars['p'] = $id;
}

All you then do is search using the regular search box using a #(hash) prefix infront of the numeric ID.

#123

..would return the post with an ID of 123.

I’m sure there’s more complicated routes that could be taken to do this, but i don’t see any issues with this approach, unless you have lots of posts with titles that start with a hash(but you could always swap the hash for another character).

Hope that helps. 🙂

Leave a Comment