doucanshou6998 2014-10-17 08:03
浏览 32
已采纳

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

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)

  • 写回答

1条回答 默认 最新

  • douhuibo5635 2014-10-17 08:36
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记