如何从WordPress url中删除自定义帖子类型? [英] how to remove custom post type from wordpress url?

查看:17
本文介绍了如何从WordPress url中删除自定义帖子类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WordPress网站,它使用带有登录和服务等自定义帖子类型的自定义模板。

每种帖子类型在URL中都有一个特定的插件,如下所示=>(http://example.com/landing/landing-page-name)

我要将此URL(http://example.com/landing/landing-page-name)更改为此URL(http://example.com/landing-page-name)。

事实上,我需要从URL中删除[登陆]短语。重要的是,[平台]是我的帖子表中的一个自定义帖子类型。

我测试了以下解决方案:

==>我已将REGISTER_POST_TYPE()中重写属性中的slug更改为‘/’-->它中断了所有登录、帖子和页面URL(404)

==>我在重写属性中添加了‘WITH_FORWARE’=>FALSE-->没有更改

==>我尝试在htAccess中使用ReWriteRule执行此操作-->它不起作用或提供太多重定向错误

我无法获得正确的结果。

以前有人解决过此问题吗?

推荐答案

首先,您需要筛选自定义帖子类型的固定链接,以便所有已发布的帖子的URL中都没有该插件:

function stackoverflow_remove_cpt_slug( $post_link, $post ) {
    if ( 'landing' === $post->post_type && 'publish' === $post->post_status ) {
        $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
    }
    return $post_link;
}
add_filter( 'post_type_link', 'stackoverflow_remove_cpt_slug', 10, 2 );
此时,尝试查看链接将导致404(找不到页面)错误。这是因为WordPress只知道帖子和页面可以有domain.com/post-name/domain.com/page-name/这样的URL。我们需要告诉它,我们的自定义帖子类型的帖子也可以有domain.com/cpt-post-name/这样的URL。

function stackoverflow_add_cpt_post_names_to_main_query( $query ) {
    // Return if this is not the main query.
    if ( ! $query->is_main_query() ) {
        return;
    }
    // Return if this query doesn't match our very specific rewrite rule.
    if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) {
        return;
    }
    // Return if we're not querying based on the post name.
    if ( empty( $query->query['name'] ) ) {
        return;
    }
    // Add CPT to the list of post types WP will include when it queries based on the post name.
    $query->set( 'post_type', array( 'post', 'page', 'landing' ) );
}
add_action( 'pre_get_posts', 'stackoverflow_add_cpt_post_names_to_main_query' );

这篇关于如何从WordPress url中删除自定义帖子类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆