I’m trying to create a custom search functionality for my WordPress site’s error page. When visitors land on a 404 page, I want to automatically display search results based on the URL they attempted to access.
Normally, the search template works with URL parameters and uses the standard WordPress loop:
I need to figure out how to programmatically set the search query instead of relying on GET parameters. Is there a way to define the search terms directly in PHP code and then run the search loop? Any help would be great!
get_posts() is another solid option that works great for custom search implementations. I use this a lot when building custom 404 pages since it returns an array of post objects without messing with the global query.
For extracting search terms from the 404 URL, I usually grab the REQUEST_URI, strip out common words like ‘the’, ‘and’, ‘of’, then combine what’s left. This gives you more control over the search logic without breaking WordPress’s main query loop. Just remember get_posts() doesn’t handle pagination automatically - you’ll need to do that separately if you want it.
you can also hook into pre_get_posts to modify the main query on your 404 page. just check if it’s the 404 template, then set your search parameters directly. i’ve done this before - works smoothly and doesn’t need extra queries.
Use WP_Query to create a custom search query programmatically. Skip the GET parameters and just instantiate a new WP_Query object with your search terms in the arguments array.
Here’s how I’ve done it in my projects:
$search_term = sanitize_text_field($your_custom_search_term);
$search_query = new WP_Query(array(
's' => $search_term,
'post_type' => 'post',
'posts_per_page' => 10
));
if ($search_query->have_posts()) {
while ($search_query->have_posts()) {
$search_query->the_post();
// Your template code here
}
wp_reset_postdata();
}
For the 404 scenario, extract keywords from the requested URL using parse_url() and explode(), then feed those as search terms. Don’t forget to sanitize any user input and call wp_reset_postdata() after your custom loop to restore the global post object.