这个问题由来已久,但问题仍然存在。从URL中删除slug的最佳方法是在functions.php
文件
另一种方法是传递重写参数,如下所示:
\'rewrite\' => array(\'slug\' => \'/\', \'with_front\' => false)
但不建议这样做,因为它会在其他页面中导致404错误。所以你应该选择进入主题的解决方案
functions.php
.
/**
* Remove the slug from published post permalinks. Only affect our CPT
though.
*/
function sh_remove_cpt_slug( $post_link, $post, $leavename ) {
if ( in_array( $post->post_type, array( \'cpt\' ) )
|| \'publish\' == $post->post_status )
$post_link = str_replace( \'/\' . $post->post_type . \'/\', \'/\', $post_link );
return $post_link;
}
add_filter( \'post_type_link\', \'sh_remove_cpt_slug\', 10, 3 );
这将从已发布帖子的URL中删除slug。这仍然会导致错误,因为它指定只有“post”和“page”post类型可以有url,而不包含post类型slug。
现在要教WP,我们的CPT也会有URL而没有slug,我们需要在我们的functions.php
function sh_parse_request_tricksy( $query ) {
// Only loop the main query
if ( ! $query->is_main_query() ) {
return;
}
// Only loop 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( \'cpt\' ) );
}
}
add_action( \'pre_get_posts\', \'sh_parse_request_tricksy\' );
参考号:
https://wordpress.stackexchange.com/a/320711/98322