如何设置永久链接以在 WordPress 中获取所有带有父帖子的子自定义帖子?

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

我为自定义帖子类型创建父子关系。

通用:www.example.com/parent/parent_post

示例:www.example.com/projects/project-one

在上面的 URL 中,父级是自定义帖子类型,父级帖子是其单个帖子。 我可以向家长显示所有帖子和单个帖子,分别为 archive-parent.php 和 single-parent.php 。

正如我之前提到的,我创建了父子关系,并使用将“post_parent”存储为父 ID 的子帖子。

通用:www.example.com/child/parent_post/child_post

样品: www.example.com/project_article/project-one/first-article

对于特定的子帖子,URL 将如上。

下面的代码用于获取特定的子帖子。并且它工作正常。

function my_add_rewrite_rules() {
    add_rewrite_tag('%child%', '([^/]+)', 'child=');
    add_permastruct('child', 'child/%parent%/%child%', false);
    add_rewrite_rule('^child/([^/]+)/([^/]+)/?','index.php?child=$matches[2]','top');
}
add_action( 'init', 'my_add_rewrite_rules' );

function my_permalinks($permalink, $post, $leavename) {
    $post_id = $post->ID;
    if($post->post_type != 'child' || empty($permalink) || in_array($post->post_status, array('draft', 'pending', 'auto-draft')))
        return $permalink;
    $parent = $post->post_parent;
    $parent_post = get_post( $parent );
    $permalink = str_replace('%parent%', $parent_post->post_name, $permalink);
    return $permalink;
}
add_filter('post_type_link', 'my_permalinks', 10, 3);

通用:www.example.com/child/parent_post

示例:www.example.com/project_article/project-one

现在我想要所有带有父帖子的子帖子,如上面的 URL 所示。

我是word-press新手,请指导。

php wordpress
1个回答
0
投票

假设

parent
作为父自定义帖子类型,
child
作为子自定义帖子类型,并希望您需要像
http://www.example.com/parent/parent-post/child/child-post
这样的子帖子 URL,而不是
http://www.example.com/child/parent-post/child-post

将您的

my_add_rewrite_rules()
函数更改为以下内容。

function my_add_rewrite_rules() {
    add_rewrite_tag('%child%', '([^/]+)', 'child=');
    add_permastruct('child', '/parent/%parent%/child/%child%', false);
    add_rewrite_rule('^parent/([^/]+)/child/([^/]+)/?','index.php?child=$matches[2]','top');
}
add_action( 'init', 'my_add_rewrite_rules' );

更新后,不要忘记通过“设置 > 永久链接”刷新永久链接。

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