首页 > 解决方案 > Wordpress 从自定义帖子中删除 Slug

问题描述

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

我想从我的自定义帖子中删除 slug,我找到了以下解决方案:

 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%/结构?

标签: phpwordpress

解决方案


在您的 function.php 中添加以下代码并更新您的 post-type

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' );

推荐阅读