0

我想要实现的目标似乎微不足道,但尚未找到解决方案:

我希望能够避免使用自定义 postype 的 slug (article即标题。site_topicblog

到目前为止已尝试更改永久链接结构:(它确实可以根据需要在仪表板交换链接中工作,但访问页面时会导致 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 );

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

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

1 回答 1

0

在您的活动主题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 );

仅仅去除蛞蝓是不够的。现在,您将获得一个 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' );

经过测试并且运行良好

于 2019-05-30T10:07:00.807 回答