Wordpress 4.0使用永久链接发送url变量

时间:2014-10-17 08:03:24

标签: php wordpress variables url permalinks

我试图在网址中发送变量。正如我已经激活固定链接一样,我正在尝试添加重写规则,正如我在此处阅读的帖子所述...

没什么可行的。这是我在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');

这是获取变量的调用。

$aid = urldecode($wp_query->query_vars['aid']);

我做错了什么? :( 我的wordpress版本是4.0(最新版)

1 个答案:

答案 0 :(得分:0)

请尝试以下代码:

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"
    );
}

最后在您的template-redirect或任何后续操作/挂钩中,您应该执行以下操作:

global $wp_query;

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

如果您无法在$ wp_query中看到这些变量,请尝试再次保存WordPress信息中心中的永久链接。这将清除网址缓存。