我想要实现的目标似乎微不足道,但尚未找到解决方案:
我希望能够避免使用自定义 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' );