首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何将特定自定义post类型的URL仅从尾部斜杠重定向为非尾部斜杠?

将特定自定义post类型的URL仅从尾部斜杠重定向为非尾部斜杠,可以通过以下步骤实现:

  1. 首先,需要在网站的主题文件(通常是functions.php)中添加以下代码:
代码语言:php
复制
function redirect_custom_post_type() {
    global $wp_rewrite;
    $custom_post_types = array('your_custom_post_type'); // 替换为你的自定义post类型

    foreach ($custom_post_types as $post_type) {
        $rule = '^' . $post_type . '/([^/]+)/?$';
        $rewrite = 'index.php?post_type=' . $post_type . '&name=' . $wp_rewrite->preg_index(1);
        add_rewrite_rule($rule, $rewrite, 'top');
    }
}
add_action('init', 'redirect_custom_post_type');
  1. 然后,需要刷新WordPress的重写规则。可以通过在WordPress后台导航到“设置”->“固定链接”页面,不做任何更改,直接点击“保存更改”按钮来实现。
  2. 最后,需要添加一个重定向规则,将带有尾部斜杠的URL重定向到非尾部斜杠的URL。可以通过在网站的主题文件中添加以下代码实现:
代码语言:php
复制
function redirect_trailing_slash($url, $status) {
    if (is_singular('your_custom_post_type') && substr($url, -1) == '/') {
        wp_redirect(rtrim($url, '/'), $status);
        exit();
    }
    return $url;
}
add_filter('redirect_canonical', 'redirect_trailing_slash', 10, 2);

请注意,上述代码中的"your_custom_post_type"需要替换为你的自定义post类型的名称。

这样,当访问特定自定义post类型的URL时,如果URL以尾部斜杠结尾,用户将被重定向到相同的URL,但尾部斜杠将被移除。

这种重定向可以提供更好的URL一致性和用户体验,同时也有助于避免搜索引擎将同一内容视为重复内容的问题。

腾讯云相关产品和产品介绍链接地址:

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券