How to add Custom Query Parameters in WordPress Programming 08 JUL 2013

wordpress-logoI’m in the process of modifying my WordPress theme such that when you click on one of the post excerpts shown on the home page, or any category page for that matter, the resulting post page shows up in a fancybox lightbox, thereby allowing you to safely and quickly open up links without worrying about losing your place on the scrolling listing page.

In order to minimize the work for myself, I intend to reuse the single.php file in my theme to display for both a standard accessed single page as well as this new lightbox view, though obviously the two views would have to be tweaked, as for example on the lightbox page, you don’t necessarily want to show the site’s header all over again!

So how does one do this? Well, the obvious answer is that we need either a $_GET or $_POST variable which we can use to distinguish the two views, which brings us to the next question: how does one add a custom query parameter to WordPress such that it’s rewrite engine understands what to do with the new parameter?

Well the answer lies in the useful query_vars filter which WordPress uses in its URL rewriting mechanism.

Locate or create the functions.php file in the root of your theme folder and add the following bit of example code:

add_filter('query_vars', 'fancybox_display_queryvars' );

function fancybox_display_queryvars( $qvars )
  $qvars[] = 'fancybox_display';
  return $qvars;

In this particular example I’m only adding one new URL parameter (fancybox_display) to those that WordPress already understands, meaning that given any URL that is suffixed with ‘?fancybox_display=1’ will result in a $_GET variable I can access and make use of.

For example, to check if it exists, and thus know we need to follow the logic dictating a lightbox layout using our example above, use the following:

if( isset( $wp_query->query_vars['fancybox_display'] )) {
 //do something 

And that’s all there is to it really.

UPDATE: Only noticed now that I’ve obviously stumbled into this problem before… Oh well, a double post shouldn’t hurt me too much I guess.

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.