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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题