WordPress PHP: How to add URL Querystring Parameters to Your Plugin CodeUnit 26 DEC 2011

WordPress is set up such that unknown URL GET parameters are ignored, a nice security/navigation feature to be sure, but an annoying one if you are developing a plugin that needs to allow for GET variables in order to control your output.

Luckily there is a solution to achieve this though… to add new allowed URL parameters to your WordPress site, simply extend the query_vars filter! :)

In practice (you add this at the top of your plugin code):


function wtap_queryvars($qvars){
    return $qvars;

Note that it is a good idea to give your accepted GET parameters unique names so that you won’t clash with already accepted and processed GET variables. In the example above, I’ve gone and prefixed everything with wtap_.

Now that your site allows GET parameters, you obviously need to make use of them. To do this, first check their existence and then grab them via the wp_query global object:

global $wp_query;
if (isset($wp_query->query_vars['wtap_year'])){
echo '<p>Year passed in url: ' . $wp_query->query_vars['wtap_year'] . '</p>';

Great. So now http://yoursite.com/plugin-page/?wtap_year=2011&wtap_month=12 will throw up something valid, instead of an annoying 404 page!


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.