WordPress 4.0 send url variables with permalinks

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

Read More
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)

Related posts

Leave a Reply

1 comment

  1. Try the following code:

    add_action('init', 'flush_urls');
    
    function flush_urls()
    {
        // Execute flush_rules() on every request can
        // slow down your entire website
        if('clean' !== get_option('flush_urls', ''))
        {
            flush_rewrite_rules();
            add_option('flush_urls', 'clean');
        }
    }
    
    add_action('init', 'register_rewrite_rules',    0);
    
    function register_rewrite_rules()
    {
        add_rewrite_tag('%aid%',         '([^/]+)');
    
        add_rewrite_rule(
            "view-article/([^/]+)/?",
            'index.php?pagename=view-article&aid=$matches[1]',
            "top"
        );
    }
    

    Finally in your template-redirect or an any later action/hook you should do the following:

    global $wp_query;
    
    echo $wp_query->query_vars['pagename'];
    echo $wp_query->query_vars['aid'];
    

    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.