December 1, 2008

Using custom URL parameters in WordPress

Filed under: Tips — Tags: , — Webopius @ 1:32 pm

Sometimes when you are building WordPress sites you need to pass a parameter via the URL like this:

http://www.mysite.com?myvar=222

The problem is that WordPress is designed to reject any URL query parameters that it doesn’t recognise so your URL parameter will be dropped before you get a chance to use it.

The solution

Step 1

We need to tell WordPress about the new parameter(s) we will be sending via the URL. We want WordPress to recognise any url parameter sent in the format ‘http://www.yoursite.com?myvar=hello’ in any page on our WordPress site.

The easiest way to do this is to create a WordPress plugin that uses a query filter to tell WordPress about new parameters. Here’s the plugin code:

<?php
/* Plugin Name: Parameter
Plugin URI: http://webopius.com/
Description: A plugin to allow parameters to be passed in the URL and recognized by WordPress
Author: Adam Boyse
Version: 1.0
Author URI: http://www.webopius.com/
*/
add_filter('query_vars', 'parameter_queryvars' );
function parameter_queryvars( $qvars )
{
$qvars[] = 'myvar';
return $qvars;
}
?>

The plugin is configured to add one new URL parameter name ‘myvar’ to WordPress. Just copy the above code to a new .php file which you then copy to the plugins directory of your WordPress install. You then need to activate the new plugin from within your WordPress admin screens.

Step 2.

Now from any WordPress page that you can add code to (e.g. Theme page) or your own standalone page that is WordPress aware you can use your variable like this:


global $wp_query;
if (isset($wp_query->query_vars['myvar']))
{
print $wp_query->query_vars['myvar'];
}

  • Tags