I’m trying to send a variable in the url. As I have the permalinks activated, I’m trying to add a rewrite rule, as said on a post I’ve read here…
Well nothing is working. This is the code I have on functions.php
add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
add_filter('query_vars','wp_insertMyRewriteQueryVars');
add_filter('init','flushRules');
// Remember to flush_rules() when adding rules
function flushRules(){
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
// Adding a new rule
function wp_insertMyRewriteRules($rules)
{
$newrules = array();
$newrules['view-article/(.+)'] = 'index.php?pagename=view-article&aid=$matches[1]';
$finalrules = $newrules + $rules;
return $finalrules;
}
// Adding the var so that WP recognizes it
function wp_insertMyRewriteQueryVars($vars)
{
array_push($vars, 'aid');
return $vars;
}
//Stop wordpress from redirecting
remove_filter('template_redirect', 'redirect_canonical');
and this is the call to get the variable.
$aid = urldecode($wp_query->query_vars['aid']);
What am I doing wrong? 🙁
My wordpress version is 4.0 (The latest)
Try the following code:
Finally in your
template-redirect
or an any later action/hook you should do the following:In case you cannot see these variables inside the $wp_query, then try to save again the permalinks in your WordPress Dashboard. This will clean out the urls cache.