繁体   English   中英

删除自定义postype base slug和前缀永久链接,使用自定义分类+帖子标题或仅发布标题

[英]Remove custom postype base slug and prefix permalink with custom taxonomy + post title or just post title

我想要实现的目标似乎相当微不足道,仍然无法找到解决方案:

我希望能够避免使用自定义postype的slu((即article )并且在永久链接中拥有自定义分类法(即site_topic )及其术语(即blog ),或者如果没有设置则避免拥有它只是正常的标题。

到目前为止,已经尝试过更改固定链接结构:(它可以在仪表板中根据需要交换链接,但访问时的页面会生成404,并且每次编辑都会刷新固定链接)。

function ms_post_types_permalink_edit( $permalink, $post, $leavename ) {

  if ( in_array( $post->post_type, [ 'article', 'template' ] ) || 'publish' == $post->post_status ) {
    $terms = wp_get_object_terms( $post->ID, 'site_topic' );
    if( $terms ){
        return str_replace( '/' . $post->post_type . '/', '/' . $terms[0]->slug . '/', $permalink );
  }
    return str_replace( '/' . $post->post_type . '/', '/', $permalink );
}
 return str_replace( '/' . $post->post_type . '/', '/', $permalink );
}

add_filter( 'post_type_link', 'ms_post_types_permalink_edit', 10, 3 );

我们想要实现的是一个工作永久链接结构,在两种情况下都适用于这些自定义postypes,同时保留其余postypes的正常永久链接结构:

domain.com/custom-taxonomy-term/custom-post-title

domain.com/post-title

作为奖励,自定义postype在注册时具有以下内容:

....
'rewrite' => [
  'with_front' => false,
  'slug' => false,
]
....

我也尝试结合以上内容同时是以下或它们的组合:

function ms_post_types_rewrite_rule() {
    add_rewrite_rule('article/([^/]*)/?$', 'index.php?article=$matches[1]', 'top');
    add_rewrite_rule('article/([^/]*)/([^/]*)?$', 'index.php?site_topic=$matches[1]&article="$matches[2]', 'top');
}

add_action('init', 'ms_post_types_rewrite_rule');

function ms_pre_get_posts( $query ) {

  if ( ! $query->is_main_query() ) {
    return;
  }

  if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
    return;
  }
  if ( ! empty( $query->query['name'] ) ) {
    $query->set( 'post_type', [ 'article' ] );
  }
}

add_action( 'pre_get_posts', 'ms_pre_get_posts' );

在活动主题function.php文件中使用以下代码

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

        $terms = get_the_terms( $post->ID, 'site_topic' );
        if ( !empty( $terms ) ){
        // get the first term
        $term = array_shift( $terms );

        if ( 'article' != $post->post_type || 'publish' != $post->post_status ) {
            return $post_link;
        }

        $post_link = str_replace( '/' . $post->post_type . '/', '/' . $terms->slug . '/', $post_link );
    }
        return $post_link;
    }
    add_filter( 'post_type_link', 'remove_ra_slug', 10, 3 );

仅仅移除slu is是不够的。 现在,你将得到一个404页面,因为WordPress只希望帖子和页面以这种方式运行。 您还需要添加以下内容:

function parse_ra_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( 'article' ) );
    }
}
add_action( 'pre_get_posts', 'parse_ra_request' );

测试并运作良好

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM