【问题标题】:Custom rewrite rules in WordpressWordpress 中的自定义重写规则
【发布时间】:2011-03-10 10:05:42
【问题描述】:

我遇到了内部 wordpress 重写规则的问题。 我已经阅读了这个帖子,但我仍然无法得到任何结果:wp_rewrite in a WordPress Plugin

我解释一下我的情况:

1) 我有一个名为“myplugin_template.php”的 page_template 与名为“mypage”的 wordpress 页面相关联。

<?php
get_header();
switch ($_GET['action']) {
  case = "show" {
  echo $_GET['say'];
  }
}
get_footer();
?>

2) 我需要为此链接创建一个重写规则:

http://myblog/index.php?pagename=mypage&action=show&say=hello_world

如果我使用这个网址,所有的东西都可以正常工作,但我想达到这个结果:

http://myblog/mypage/say/hello_world/

我真的不想破解我的 .htaccess 文件,但我不知道如何使用内部 wordpress 重写器来做到这一点。

【问题讨论】:

    标签: wordpress mod-rewrite rewrite


    【解决方案1】:

    您需要添加自己的重写规则和查询变量 - 在 functions.php 中弹出这个;

    function my_rewrite_rules($rules)
    {
        global $wp_rewrite;
    
        // the slug of the page to handle these rules
        $my_page = 'mypage';
    
        // the key is a regular expression
        // the value maps matches into a query string
        $my_rule = array(
            'mypage/(.+)/(.+)/?' => 'index.php?pagename=' . $my_page . '&my_action=$matches[1]&my_show=$matches[2]'
        );
    
        return array_merge($my_rule, $rules);
    }
    add_filter('page_rewrite_rules', 'my_rewrite_rules');
    
    
    function my_query_vars($vars)
    {
        // these values should match those in the rewrite rule query string above
        // I recommend using something more unique than 'action' and 'show', as you
        // could collide with other plugins or WordPress core
        $my_vars = array(
            'my_action',
            'my_show'
        );
    
        return array_merge($my_vars, $vars);
    }
    add_filter('query_vars', 'my_query_vars');
    

    现在在您的页面模板中,将$_GET[$var] 替换为get_query_var($var),就像这样;

    <?php
    get_header();
    switch (get_query_var('my_action')) {
        case = "show" {
            echo esc_html(get_query_var('my_say')); // escape!
        }
    }
    get_footer();
    ?>
    

    【讨论】:

    • 规则不应该是mypage/([^/]+)/([^/]+)/?吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    • 2019-05-10
    • 2015-08-17
    相关资源
    最近更新 更多