display text generated via custom get query string

You should not use the query var API for that, use $_GET or filter_input instead. get_query_var is for accessing parameters on the main WP_Query, not for retrieving URL GET parameters. Using this API for URLs is misleading and can trigger lots of unexpected problems.

The query variable API is for rewrite rules and WP_Query, e.g. for handling custom permalinks and virtual pages, etc. It was never intended for retrieving raw URL parameters in templates like that.

get_query_var will retrieve the value of the requested parameter that was used in the main query. That value may differ from the URL, or it may return a value despite not being in the URL at all. It can also be modified and intercepted via filters such as pre_get_posts or parse_request.

Another example is that if I visit /mypage?foo=bar then run this code:

query_post('s=test');
echo get_query_var( 'foo' );

It will not print bar, because the current main query does not contain a foo query variable.


As for why your example does not work, the problem is that by the time your page template has loaded, the query variables filter has already run! The main query has already ran, it’s already fetched your page, and already decided on the template to load. Your filter has been added yes, but the filter ran a long time ago, your code is waiting to board a train that has already left!

Generally, actions and filters don’t belong in templates and are almost always a sign that a mistake has been made or that the user doesn’t understand that actions/hooks/filters aren’t a domain language, and that events on a timeline is a more accurate mental model. add_actionn( 'init', 'foobar' )' is equivalent to _from now on, if the init event happens, call foobar.

It’s not what you did, it’s when you did it. Put your filters/actions in a plugin or functions.php instead