Wordpress 永久链接自定义结构不适用于子类别

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

我正在为一个作品集网站开发 WordPress 主题。我有很多帖子,这些项目有“项目”类别,但也有“视频”或“摄影”等子类别。我有一个“项目”类别的存档页面,显示所有“项目”帖子,在此页面上,我还有一个目录,其中包含“项目”下的所有子类别的列表,我想链接到每个项目子类别存档页面。

一切都很顺利,直到我编辑了永久链接结构。

我希望“项目”存档页面永久链接如下所示:

domain.com/projects/

为此,我使用了

/%category%/%postname%/
的自定义结构,并在类别基础上编写了
.
(一个点),以从永久链接中隐藏“类别”(否则它看起来像:
domain.com/category/projects/
)。 因此,现在子类别的链接不起作用,因为子类别永久链接是:
domain.com/subcategory/
,但“项目”下的子类别目录链接到:
domain.com/projects/subcategories/

关于如何更改子类别永久链接或子类别目录上的实际链接有什么想法吗?

其他背景:
我这样称呼这个子类别列表:

<?php
$category = get_category_by_slug( 'projects' );
wp_list_categories('child_of='.$category->term_id);
?>
php wordpress structure categories permalinks
1个回答
0
投票

Hey André 要实现这个永久链接结构并确保子类别目录中的链接正常工作,您可以使用 WordPress 中的 post_link 和 post_type_link 过滤器。

这些过滤器将允许您修改帖子和自定义帖子类型的永久链接结构。

这是一个示例函数,应该可以为您提供所需的结果。

function custom_projects_permalink_structure($post_link, $post, $leavename, $sample) {
    // Check if the post type is 'projects'
    if ($post->post_type === 'projects') {
        // Get the category terms for the post
        $terms = get_the_terms($post->ID, 'category');
        
        // Check if there are category terms
        if ($terms && !is_wp_error($terms)) {
            // Get the first category term
            $category = array_shift($terms);
            
            // Build the new permalink structure
            $post_link = home_url('/' . $category->slug . '/' . $post->post_name . '/');
        }
    }

    return $post_link;
}

add_filter('post_type_link', 'custom_projects_permalink_structure', 10, 4);

修改上述内容并将其保存在插件或主题functions.php文件中

转到 WordPress 管理仪表板中的“设置”>“永久链接”,然后单击“保存更改”以刷新永久链接结构。

注意:在进行任何更改之前,请务必备份您的functions.php 文件,并彻底测试以确保一切按预期工作。

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