support

WordPress permalinks and passing custom Variables to it

Sometimes we need a simple way of passing a custom variable(s) to WordPress. WordPress has a organised way in this respect as it passes a lot of arguments in URL, so unless you want to grub around directly with the $_GET array, then this solution is a little more elegant.

First look at the code:


function add_query_vars($aVars) {
$aVars[] = "myVar"; // represents the name of the custom variable you want to add in URL
return $aVars;
}

add_filter('query_vars', 'add_query_vars');

function add_rewrite_rules($aRules) {
$aNewRules = array('mypage/([^/]+)/?$' => 'index.php?pagename=mypage&myVar=$matches[1]');
$aRules = $aNewRules + $aRules;
return $aRules;
}

add_filter('rewrite_rules_array', 'add_rewrite_rules');

Explanation:


function add_query_vars($aVars) {
$aVars[] = "myVar"; // represents the name of the custom variable you want to add in URL
return $aVars;
}

add_filter('query_vars', 'add_query_vars');

This function tells wordpress that we are going to pass a custom variable in the url. тАЬmyVarтАЭ will be the name of our custom variable so basicly our URL will be : тАЬhttp://www.wordpresswebsite.com?page_id=3&myVar=myvalueтАЭ. add_filter just initializes this function for wordpress to run it.

function add_rewrite_rules($aRules) {
$aNewRules = array('mypage/([^/]+)/?$' => 'index.php?pagename=mypage&myVar=$matches[1]');
$aRules = $aNewRules + $aRules;
return $aRules;
}

add_filter('rewrite_rules_array', 'add_rewrite_rules');

This function does the following:

1. It will check for the page name, so we have to specify what page it will be on, the permalink will be http://www.wordpressite.com/mypage/

2. It tells wordpress that everything after that pagename (mypage) will be the VALUE of the variable NAME (myVar) added in the previous function.

To Implement this you dump that code into your function.php (if you are going to use this in a template) or you plugin file (if you will use it in your plugin). Then in your code you can reference a link called http://www.wordpresssite.com/mypage/myvarValue/.

If you set the тАЬadd_query_varsтАЭ function to myvar your query string would normally look like:
http://www.wordpressite.com/?page_id=3&myvar=myvalue.
But now it will look like:
http://www.wordpresssite.com/mypage/myvalue.

Note: If the above functions will not work then You must go to Settings->Permalinks and save changes before changes will be applied. Permalinks settings can be anything you were using for your WordPress website.

© 2008-2021 Copyright Startbit IT Solutions Pvt. Ltd.(Formerly known as Vivacity InfoTech Pvt. Ltd.) | All Rights Reserved.
Loading...