Wordpress中的自定义重写规则 [英] Custom rewrite rules in Wordpress
问题描述
我在内部wordpress重写规则方面遇到了麻烦. 我已经阅读了该线程,但仍然无法获得任何结果:
I'm in trouble with the internal wordpress rewrite rules. I've read this thread but I still can't get any results: wp_rewrite in a WordPress Plugin
我解释一下我的情况:
1)我有一个名为'myplugin_template.php'的page_template与一个名为"mypage"的wordpress页面相关.
1) I have a page_template called 'myplugin_template.php' associated to a wordpress page called "mypage".
<?php
get_header();
switch ($_GET['action']) {
case = "show" {
echo $_GET['say'];
}
}
get_footer();
?>
2)我需要为此链接创建一个重写规则:
2) I need to create a rewrite rule for this link:
http://myblog/index.php?pagename = mypage& ; action = show& say = hello_world
如果我使用此url,所有的东西都可以正常工作,但是我想实现以下结果:
If I use this url all the things works without problems but I'd like to achieve this result:
http://myblog/mypage/say/hello_world/
我真的不想破解我的.htaccess文件,但我不知道如何使用内部wordpress重写器来做到这一点.
I really don't want to hack my .htaccess file but I don't know how I can do this with the internal wordpress rewriter.
推荐答案
您需要添加自己的重写规则并查询vars-在functions.php
;
You'll need to add your own rewrite rule and query vars - pop this in 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)
;
Now in your page template, replace $_GET[$var]
with get_query_var($var)
like so;
<?php
get_header();
switch (get_query_var('my_action')) {
case = "show" {
echo esc_html(get_query_var('my_say')); // escape!
}
}
get_footer();
?>
这篇关于Wordpress中的自定义重写规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!