admin管理员组文章数量:1426292
my posts have urls of two different types: one with post id and other with post slug:
/post/789
/post/my-post-slug
i'm doing this using:
add_rewrite_rule(
'post/(\d+)/?',
'index.php?p=$matches[1]',
'top'
);
and setting up permalinks using %post_name%.
both /post/123
and /post/my-post-slug
open the same html page.
is it possible to make wordpress return the 301 redirect to /post/my-post-slug
when accessing /post/123
?
my posts have urls of two different types: one with post id and other with post slug:
/post/789
/post/my-post-slug
i'm doing this using:
add_rewrite_rule(
'post/(\d+)/?',
'index.php?p=$matches[1]',
'top'
);
and setting up permalinks using %post_name%.
both /post/123
and /post/my-post-slug
open the same html page.
is it possible to make wordpress return the 301 redirect to /post/my-post-slug
when accessing /post/123
?
1 Answer
Reset to default 0yes, it is possible. add a template_redirect
hook handler:
add_filter('template_redirect', 'redirect_post_to_canonical_url');
function redirect_post_to_canonical_url(): void
{
if (!is_single()) {
// do not redirect nothing else except posts
return;
}
$canonicalLocation = get_permalink();
$requestUri = $_SERVER['REQUEST_URI'];
$currentLocation = home_url('/') . substr($requestUri, 1);
if ($currentLocation === $canonicalLocation) {
// prevent from infinite redirect loop
return;
}
wp_redirect($canonicalLocation, 301);
}
本文标签: categoriesHow to 301 redirect from url with post id to permalink with post name (slug)
版权声明:本文标题:categories - How to 301 redirect from url with post id to permalink with post name (slug)? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745475015a2659922.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论