首页 > 解决方案 > 删除自定义帖子类型 Slug 但如果有父级,请将其保留在 URL 中

问题描述

我注册了一个自定义帖子类型,将重写设置为 'rewrite' => array( 'with_front' => true ) ,并使用以下方法从中删除了 slug:

function my_remove_slug( $post_link, $post, $leavename ) {

    if ( 'content_hub' != $post->post_type || 'publish' != $post->post_status ) {
        return $post_link;
    }

    $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );

    return $post_link;
}
add_filter( 'post_type_link', 'my_remove_slug', 10, 3 );


function my_parse_request( $query ) {

    if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
        return;
    }

    if ( ! empty( $query->query['name'] ) ) {
        $query->set( 'post_type', array( 'post', 'content_hub', 'page' ) );
    }
}
add_action( 'pre_get_posts', 'my_parse_request' );

这对于不包含父级的 URL 非常有效,但是它也会重写包含父级的 URls。

例如:

mydomain.com/parent-slug/child-slug

这将返回 404。

然而,没有 parent-slug 的相同 url 加载。

我需要对其进行更改,以便在 URL 中仍包含 parent-slug(如果存在)。

我试过这样的事情:

function my_remove_slug( $post_link, $post, $leavename ) {

    if ( 'content_hub' != $post->post_type || 'publish' != $post->post_status ) {
        return $post_link;
    }

        $post_link = str_replace( '/' . $post->post_type . '/', '/' . $parent_slug . '/', $post_link );

    return $post_link;
}
add_filter( 'post_type_link', 'my_remove_slug', 10, 3 );

但这会将网址返回为:

mydomains.com/parent-slug/parent-slug/child-slug

并且仍然显示404。

标签: wordpresscustom-post-typepermalinks

解决方案


推荐阅读