Not too long ago I was assigned a task that involved a bit of back-end magic. Part of the assignment called for creating a page that would display the name of a US State passed in a URL parameter. The issue with parameters in WordPress is that, aside from the built-in search param, WordPress tosses out any parameter when passed through a URL. So what solution do we have here?

I came across a bunch of potential solutions, but being a fan of Occam’s Razor, I decided to go with the most simple for the task. The guys over at Webopius detailed a very quick and elegant solution for using custom URL parameters within WordPress. Their solution allows you to easily retrieve a custom parameter from any template using a function. This was a great step forward but I wanted to call the parameter from the page’s content, not from template. I was looking for a user-friendly way so that the content’s author could easily insert the parameter’s value at her own convenience.

In order to achieve this I used the above solution in combination with the URL Params plugin. This little plugin allows you to insert a URL parameter by using a simple shortcode:

[urlparam param="paramname" default="Value" /]

The Solution

The first step is to install the URL Params plugin and activate it. Then head over to Plugins -> Editor and select the URL Params plugin from the dropdown list.

Click on the urlparams.php file and insert the following code right after the add_shortcode() calls:

function parameter_queryvars( $qvars ) { 
    $qvars[] = 'paramname';
    return $qvars; 
}

Use the name of the key you want to create for paramname. In my case it was state. Remember to save your change and then that’s it.

Now you can navigate without worries to www.mysite.com/my-state/?state=Texas and you’ll see the state’s name proudly showing up wherever you placed the [urlparam] shortcode.

 

It’s worth noting that this is a quick and simple solution that doesn’t process the parameter values and only applies to the key you defined in the parameter_queryvars function, but based on this you can insert any additional logic you need depending on your own requirements.

Happy coding!