问题描述
我试图让我的页面接收查询变量,但将其重写为漂亮的永久链接.所以我想要这个
I'm trying to allow my page to receive query variable but to rewrite it to nice permalink. So I wanted this
example.com/wordpress-page/random
所以我不希望 random
成为子页面或类似的东西,因为它来自外部服务.为了做到这一点,我已将此代码添加到我的 functions.php
So I don't want random
to be a subpage or something like that, since it's coming from outside service. In order to do this, I've added this code to my functions.php
function add_my_var($public_query_vars) {
$public_query_vars[] = 'my_var';
return $public_query_vars;
}
add_filter('query_vars', 'add_my_var');
function do_rewrite() {
add_rewrite_rule('wordpress-page/([^/]+)/?$', 'index.php?name=wordpress-page&my_var=$matches[1]','top');
}
add_action('init', 'do_rewrite');
当我去 example.com/wordpress-page
时我得到我的页面,但是当我去 example.com/wordpress-page/random
时我得到 404页.
When I go to example.com/wordpress-page
I get my page, but when I go to example.com/wordpress-page/random
I get 404 page.
我通过在 wp-admin
面板中保存永久链接来刷新重写规则.
I have flushed rewrite rules by saving permalinks in wp-admin
panel.
我哪里做错了?
推荐答案
我发现我需要调用 flush_rewrite_rules() 函数.除了上面已经演示的 query_vars
动作挂钩和 add_rewrite_rule()
函数之外,还完成了这项工作.
I found I needed to call the flush_rewrite_rules() function. That was done in addition to the query_vars
action hook and add_rewrite_rule()
function you already demonstrated above.
在我的例子中,我选择使用 switch_theme 操作将它放在我的主题的functions.php 中挂钩并停用/重新激活我的主题.但是你可以把它放在别处,只要它在某个时候被调用一次(所以可能不是'init')
In my case I chose to put it in my theme's functions.php using the switch_theme action hook and deactivated/reactivated my theme. But you can probably put it elsewhere as long as it get's called once at some point (so probably not 'init')
add_action('switch_theme', 'mytheme_setup_options');
function mytheme_setup_options () {
flush_rewrite_rules();
}
这篇关于将自定义 URL 段添加到 wordpress 页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!