dongyi1777 2018-07-12 10:37
浏览 37

Wordpress从自定义帖子中删除Slug

My Permalink structure is set to be: %category%/%postname%/

I want to remove the slug from my custom post and I found the following solution:

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

However, it works only when my permalink is set to /%postname%/

Any ideas how to make it works with: %category%/%postname%/ structure?

  • 写回答

2条回答 默认 最新

  • dtyw10299 2018-07-12 10:42
    关注

    Add the following code in your function.php and update your-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' );
    
    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错