将 WordPress 中没有类别的 URL 重定向到有类别的 URL

问题描述 投票:0回答:1

到目前为止,我一直在尝试执行此重定向,但没有成功。我有一个 WordPress 网站,我的 URL 目前遵循以下模式:

https://example.com/slug-title/

我需要将它们更改为这种模式:

https://example.com/post-category/slug-title/

我想找到一种方法来动态地执行此操作而不损害我的搜索引擎优化。我尝试在我的functions.php中创建此代码,但它不起作用:

还有其他方法可以执行此重定向吗?我不想使用插件来执行此操作。

我感谢任何帮助和想法。

add_action('template_redirect', 'custom_category_redirect');
function custom_category_redirect() {
    if (is_single() && !is_admin()) {
        global $post;
        $categories = get_the_category($post->ID);
        if (!empty($categories)) {
            $category_slug = $categories[0]->slug; // Gets the slug of the first category of the post
            $current_url = $_SERVER['REQUEST_URI']; // Gets the current URL
            $current_slug = basename(get_permalink($post->ID)); // Gets the current slug
            $new_url = home_url("/$category_slug/$current_slug/"); // Target URL with the category slug
            if (home_url(add_query_arg(array())) !== $new_url) {
                wp_redirect($new_url, 301); // Permanently redirects
                exit;
            }
        }
    }
}
wordpress redirect
1个回答
0
投票

而不是这个

add_action('template_redirect', 'custom_category_redirect');

用这个

add_action('wp', 'custom_category_redirect');

template_redirect发生在发送标头之前,导致重定向发生得太晚,wp钩子在WordPress完成加载之后但在发送任何标头之前调用。

注意:我更喜欢 .htaccess 重定向和永久链接更改。它更容易,更快,使用更少的资源。您可以更新永久链接以支持您的新网址,并将所有旧网址添加为重定向(而不是重写)。 .htaccess

© www.soinside.com 2019 - 2024. All rights reserved.