Wordpress从自定义帖子中删除Slug

时间:2018-07-12 10:37:03

标签: php wordpress

我的永久链接结构设置为:%category%/%postname%/

我想从我的自定义帖子中删除该子弹,发现以下解决方法:

 function gp_add_cpt_post_names_to_main_query( $query ) {
    // Bail if this is not the main query.
    if ( ! $query->is_main_query() ) {
        return;
    }
    // Bail if this query doesn't match our very specific rewrite rule.
    if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) {
        return;
    }
    // Bail 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', 'credit-cards' ) );
}
add_action( 'pre_get_posts', 'gp_add_cpt_post_names_to_main_query' );

但是,仅当我的永久链接设置为/%postname%/

时,它才有效

有什么想法可以使它与%category%/%postname%/结构一起使用吗?

2 个答案:

答案 0 :(得分:0)

在您的function.php中添加以下代码,并更新您的帖子类型

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

    if ( ! in_array( $post->post_type, array( 'event' ) ) || 'publish' != $post->post_status )
        return $post_link;

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

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

function vipx_parse_request_tricksy( $query ) {

// Only noop the main query
if ( ! $query->is_main_query() )
    return;

// Only noop our very specific rewrite rule match
if ( 2 != count( $query->query )
    || ! isset( $query->query['page'] ) )
    return;

// 'name' will be set if post permalinks are just post_name, otherwise the page rule will match
if ( ! empty( $query->query['name'] ) )
    $query->set( 'post_type', array( 'post', 'your_post_type', 'page' ) );
}
    add_action( 'pre_get_posts', 'vipx_parse_request_tricksy' );

答案 1 :(得分:0)

以下代码将起作用,但是您只需要记住,如果自定义帖子类型的信息与页面或信息的信息相同,则冲突很容易发生...

首先,我们将从永久链接中删除该子弹:

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

    if ( 'events' != $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', 'na_remove_slug', 10, 3 );

仅仅去除弹头是不够的。现在,您将获得404页面,因为WordPress只希望帖子和页面具有这种行为。您还需要添加以下内容:

function na_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', 'events', 'page' ) );
    }
}
add_action( 'pre_get_posts', 'na_parse_request' );

只需将“事件”更改为自定义帖子类型,就可以了。您可能需要刷新永久链接。