首页 > 解决方案 > 从分层自定义帖子类型中删除基本 slug

问题描述

干杯,

出于 SEO 原因,我尝试删除自定义分层服务帖子类型的基本 slug(示例名称:“custom-service”)。这些方法称为 SEO 筒仓。我尝试了不同的方法来获得以下 url 结果。

它不应该看起来如何:

https://foo.bar/custom-service/seo-agency/

https://foo.bar/custom-service/seo-agency/seo-workshop/

https://foo.bar/custom-service/foobar-agency/

https://foo.bar/custom-service/foobar-agency/foobar-workshop/

它应该看起来如何:

https://foo.bar/seo-agency/

https://foo.bar/seo-agency/seo-workshop/

https://foo.bar/foobar-agency/

https://foo.bar/foobar-agency/foobar-workshop/

我使用以下教程来实现这些结构:

有一些人有同样的问题:

起初,我已经实现了 Matthew Boynes 的第一个教程的解决方案。一切正常,除了我的分页。如果我使用这些解决方案,我的分页将停止工作。函数中的以下代码可能add_rewrites()会破坏分页:

add_permastruct( 'custom-service', "%custom-service%", array(
    'ep_mask' => EP_PERMALINK
));

你不能调用我博客的页面。以下网址停止工作:

https://foo.bar/blog/page/2
https://foo.bar/cpt/page/2

在我的第二次尝试中,我删除了 Matthew Boynes 代码。在其存档中没有分页的博客是没有用的。然后我实施了来自“kellenmace.com”的解决方案。要使代码适用于分层帖子类型,您必须修改教程过滤器功能post_type_link

function remove_custom_service_slug( $post_link, $post ) {
    if ( 'custom-service' === $post->post_type && 'publish' === $post->post_status ) {
        if( $post->post_parent ) {
            $parent = get_post($post->post_parent);
            $post_link = str_replace( '/' . $post->post_type . '/' . $parent->post_name . '/', '/', $post_link );
        } else {
            $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
        }
    }
    return $post_link;
}
add_filter( 'post_type_link', 'remove_custom_service_slug', 10, 2 );

但是有一个大问题。它删除了基本 slug父服务 slug:

https://foo.bar/seo-agency/

https://foo.bar/seo-workshop/

它有点令人沮丧。也许有人有删除分层帖子类型的基本 slug 的经验,并且对我的项目有很好的提示。


如果您有任何问题,或者您想了解更多信息或代码,请随时与我联系。

感谢您阅读我的问题!

标签: phpwordpressurl-rewritingpermalinks

解决方案


将函数更改为此以考虑所有情况:

试试这个代码,

function change_slug_struct( $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', 'single-link', 'page' ) );
    } elseif ( ! empty( $query->query['pagename'] ) && false === strpos( $query->query['pagename'], '/' ) ) {
        $query->set( 'post_type', array( 'post', 'single-link', 'page' ) );

        // We also need to set the name query var since redirect_guess_404_permalink() relies on it.
        $query->set( 'name', $query->query['pagename'] );
    }
}
add_action( 'pre_get_posts', 'change_slug_struct' );


推荐阅读