Search Using Post ID

I previously asked and answered my own question about customizing a search. You can find that answer here: The right way to create a custom search page for complex custom post types. It’ll be a good read to help you understand the following code.

I’ll use the pre_get_posts action to change your search when you are searching for a positive integer. Note that the code I’m providing will not allow you to search for positive integers within your article.

function my_search_pre_get_posts($query)
{
    // Verify that we are on the search page that that this came from the event search form
    if($query->query_vars['s'] != '' && is_search())
    {
        // If "s" is a positive integer, assume post id search and change the search variables
        if(absint($query->query_vars['s']))
        {
            // Set the post id value
            $query->set('p', $query->query_vars['s']);

            // Reset the search value
            $query->set('s', '');
        }
    }
}

// Filter the search page
add_filter('pre_get_posts', 'my_search_pre_get_posts');

If you want to be able to search for ID and a search string, I would recommend including multiple inputs. You can also use other logic within the function provided to make assumptions about what the user is looking for and alter the query variables accordingly.

Note that this code is untested.

Leave a Comment