WordPress Code Snippets

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.

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:

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:

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 use get_search_query(). For attributes use esc_html(get_search_query(false)).


Learn more

WordPress Themes In Depth

Show Support

Like our new Facebook Page to show support!