WP-Mix

A fresh mix of code snippets and tutorials

Proper usage of get_search_query()

This tutorial explains the two ways to properly use WordPress’ template tag, get_search_query(), depending on context. Note that the information provided in this post also applies to the similar tag, the_search_query().

Case 1: get_search_query() in markup

When using get_search_query() in HTML markup (as opposed to an attribute), it is best practice to set the tag’s $escaped parameter to false, for example:

<h3>Search Results for: 
	<?php echo esc_html(get_search_query(false)); ?>
</h3>

Here the output is included within an HTML element rather than an attribute, so we want to escape it using esc_html() instead of esc_attr(), which is used by WordPress when the $escaped parameter is omitted or set to true (its default value). The difference is subtle, but is important to escape data properly depending on context.

Case 2: get_search_query() in attributes

When using get_search_query() in HTML attributes, the correct usage is to set the $escaped parameter to true, which happens to be its default value. So when using in HTML attributes, either of the following is correct:

<h3 data-search="<?php echo get_search_query(true); ?>">
	Search Results
</h3>
<h3 data-search="<?php echo get_search_query(); ?>">
	Search Results
</h3>

In either of these cases it is not necessary to escape the output of get_search_query() because WordPress passes it through esc_attr(). See the WP Codex for more details.

Take-home message

  • For HTML/markup use esc_html(get_search_query(false))
  • For attributes use get_search_query()

References

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress