gpt4 book ai didi

regex - WordPress add_rewrite_rule 在本地运行,但不在服务器上运行

转载 作者:行者123 更新时间:2023-12-04 10:39:06 24 4
gpt4 key购买 nike

我可以得到 add_rewrite_rule使用 MAMP 在本地工作,但不在我的 DreamHost 生产服务器上工作。

我正在尝试美化个人宠物的网址 http://www.pawsnewengland.com/our-dogs-list/ .丑陋的 URL 遵循以下结构:our-dogs-list/?view=pet-details&id=12345,自定义函数使用 $_GET信息中要处理的变量。

在我的 functions.php文件,我已经包含了这个:

function rewrite_pet_url() {
add_rewrite_rule(
"our-dogs-list/pet-details/([0-9]+)/?$",
"index.php/our-dogs-list/?view=pet-details&id=$1",
"top"
);
}
add_action( 'init', 'rewrite_pet_url');

我也试过这个,结果相同:
function rewrite_pet_url() {
add_rewrite_rule(
"our-dogs-list/pet-details/([0-9]+)/?$",
"index.php/our-dogs-list/?view=pet-details&id=$matches[1]",
"top"
);
}
add_action( 'init', 'rewrite_pet_url');

为了简单地测试重写是否有效,尝试了这个:
function rewrite_pet_url() {
add_rewrite_rule(
"fake",
"index.php/about",
"top"
);
}
add_action( 'init', 'rewrite_pet_url');

我正在测试之前刷新重写规则,并确认重写规则已添加到 .htaccess文件。但是,出于某种原因,我看到的是 404 页面或白屏以及“未指定输入文件”。

我能够在本地运行它,所以我不知道实时服务器上发生了什么。任何见解?

更新 1

我已经得到重写“工作”,因为它不再导致任何错误。不幸的是,它现在会导致不需要的重定向到根 URL。
function rewrite_pet_url() {
add_rewrite_tag('%view%','([^&]+)');
add_rewrite_tag('%id%','([^&]+)');
add_rewrite_rule(
'our-dogs-list/pet-details/([0-9]+)?$',
'index.php/?page_id=1663&view=pet-details&id=$1',
'top'
);
}
add_action( 'init', 'rewrite_pet_url' );

有了这个,我可以访问 viewid变量使用 get_query_var() .然而,而不是尊重 example.com/our-dogs-list/pet-details/12345 , WordPress 将页面重定向到 example.com/our-dogs-list/ .

知道是什么原因造成的吗?它有效地使重写规则无用。

最佳答案

作为评论添加太久了。

我会将此添加到functions.php。我已经改变了你的永久链接,我的 demo plugin解释每个函数的作用:

add_filter('generate_rewrite_rules', 'pet_rewrite_url');
add_filter('query_vars', 'pet_query_vars'));
add_filter('admin_init', 'pet_flush_rewrite_rules');
add_action("parse_request", "pet_parse_request");


function pet_rewrite_url( $wp_rewrite ) {
$new_rules = array(
'our-dogs-list/pet-details/([0-9]+)/?$' => sprintf("index.php?pet-details=%s",$wp_rewrite->preg_index(1))
);

$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
return $wp_rewrite->rules;
}

function pet_query_vars( $query_vars ) {
$query_vars[] = 'pet-details';
return $query_vars;
}

function pet_flush_rewrite_rules() {
$rules = $GLOBALS['wp_rewrite']->wp_rewrite_rules();
if ( ! isset( $rules['our-dogs-list/pet-details/([0-9]+)/?$'] ) ) { // must be the same rule as in pet_rewrite_url($wp_rewrite)
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
}

function pet_parse_request($wp_query) {
if (isset($wp_query->query_vars['pet-details'])) { // same as the first custom variable in pet_query_vars( $query_vars )
// add your code here, code below is for this demo
printf("<pre>%s</pre>",print_r($wp_query->query_vars,true));
exit(0);
}
}

关于regex - WordPress add_rewrite_rule 在本地运行,但不在服务器上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20363725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com