Passing a query string to your WordPress site and show something useful

Objective:

Say my website runs on Word Press (henceforth known as WP) at

http://www.abcdxyz.com


A post might look like the following

http://www.abcdxyz.com/?page_id=21

And the post gets rendered nicely. Say I want to pass a Query String (henceforth known as QS) test=1, based on which I want to show a plain text to user or in other words simple want to hook on to WP rendering technique and modify it. My intended URL becomes

http://www.abcdxyz.com/?test=21

Normally if you call this, WP would render the default page to you and simply dispose off your idea of passing and doing something useful with QS.

Solution:

We have to modify the $query_vars, a mechanism of WP internals, with hook.

1. In your plug in file write the following hooks

add_filter('rewrite_rules_array', 'add_new_allowed_qs');

You may define the body of the function as follows:

function add_new_allowed_qs( $query_vars ){
array_push($query_vars, 'test');

// return
return $query_vars;
}

2. Define the hook which would let us do anything useful with our QS

add_filter('query_vars', array($this,'add_query_vars'));

The body of this function might look like

function mgf_parse_query(){
global $wpdb, $wp_query;

if(isset($wp_query->query_vars['test'] )){
// process
echo 'test is one of the QSs and hence we echo this';
}
}


Thus you can do anything with literally a dynamic page being created in the run time.
Do leave your comments and suggestions if you feel appropriate.

Cheers!

Comments

Popular posts from this blog

uTorrent: Data error (cyclic redundancy check)

Photo upload to Facebook from your PHP web application

Khude Jajabor Istasi