I’d like to be able to enter a post ID into the search box in order for the exact post to be returned in the search results. I’d also like to retain the ability to search the posts/page titles and content.
eg, user enters ‘#123’ in the search box, and the search results return just post 123. However, if I were to enter ‘123’ into the search box, it would return any post/page that contains ‘123’ in the content or title.
This article explains how to achieve what i’m after within the Admin – I just need the equivalent for the front-end!
Any help is greatly appreciated, thank you.
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.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.
You can use this
This is untested, check the code comments: