How to Display Search Query in the Search Box and Results Page on WordPress

Home » Snippets » How to Display Search Query in the Search Box and Results Page on WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Having a functional search feature is fundamental to improving the user experience on your WordPress website. When a visitor performs a search, they would typically want to see the query that they’ve made within the search box and on the results page. This not only makes their search process more transparent, but it also enables them to keep track of what they have searched for. In this article, we will guide you on how to show the search query in the search box itself and on the resulting page, strengthening your site’s usability in the process.

					function wpturbo_show_search_query($query) {
    if ('' != $query) {
        return $query;
    }

    return get_search_query();
}

add_filter('get_search_query', 'wpturbo_show_search_query');
				

Let’s analyze this code snippet. It starts with the definition of a new function wpturbo_show_search_query($query). This function takes an argument $query, which represents the search term entered by a user.

Inside the function, there is an if condition that checks if the $query variable is not empty. To understand the condition better, let’s delve into each part. ' ' != $query is a comparison operator that checks whether $query is not equal to an empty string.

Here’s the logic: If the $query variable is not empty, which means a user has entered some search term, the function will simply return $query. Now if $query is empty, which means a user has not provided any input, it will return get_search_query(). This get_search_query() is a WordPress function that retrieves the search query string which was sent to the search page.

Now, the last part of the code snippet add_filter('get_search_query', 'wpturbo_show_search_query'); involves a WordPress Hook. Hooks in WordPress allow developers to tie their own code into the WordPress core code at specific points to change the default behavior. In this case, ‘add_filter’ hook is used.

Here, the ‘get_search_query’ is the filter. It is a tag where our custom function wpturbo_show_search_query is hooked. So, whenever WordPress runs the get_search_query() function to retrieve the search query, our wpturbo_show_search_query function modifies or filters its output before it’s returned to the search page.

This function essentially makes sure that when a user lands on the search results page, their original search query remains displayed in the search box while they browse the results. That way, they can see what their original query was even as they view the results.

Register an account to save your snippets or go Pro to get more features.