我已经使用WordPress自己的函数设置了一个重写规则。重写代码如下所示:
add_rewrite_rule('^testrule/(.+)?$', 'index.php?p=$matches[1]', 'top');
该规则有效,一切都有效,只是每当我转到该 URL 时,我都会被重定向,这使得 URL 发生变化,我不希望这种情况发生。
有什么提示吗?
您可能应该使用add_permastruct并add_rewrite_tag函数,它对我的情况有所帮助。虽然我的情况有点不同,但想法会相似。
我有名为"guide"的自定义帖子类型,我需要它的自定义 URL(与自定义帖子名称不同),而且我在 URL 中使用帖子 slug,这是我的解决方案:
add_action('init', 'custom_permastruct_rewrite');
function custom_permastruct_rewrite() {
global $wp_rewrite;
$wp_rewrite->add_rewrite_tag("%guide_slug%", '([^/]+)', "post_type=guide&name=");
$wp_rewrite->add_permastruct('my_rule', '/my_custom_name/%guide_slug%', false);
}
因此,当您转到该地址时:http://example.com/my_custom_name/my_post_slug在上述 URL 下,它显示来自以下内容的内容:http://example.com/?post_type=guide&name=my_post_slug(不重定向到最后一个地址)
您可以根据需要调整"post_type=guide&name=",例如,您可以按id查找帖子 - 因此放置"p="将显示以下内容:http://example.com/my_custom_name/24 到 http://example.com/?p=24
一些插件(如自定义永久链接)可以重定向到correct
网址
add_rewrite_rule('^testrule/(.+)?$', 'index.php?disable_redirect=1&p=$matches[1]', 'top');
add_filter('query_vars', 'my_public_query_vars');
function my_public_query_vars($qv)
{
$qv[] = 'disable_redirect';
return $qv;
}
add_filter('wp_redirect', 'my_disable_redirect');
function my_disable_redirect($location)
{
//var_dump(debug_backtrace());//if you want know who call redirect
$disable_redirect = get_query_var('disable_redirect');
if(!empty($disable_redirect)) return false;
return $location;
}