[英]WordPress change or remove custom post slug from url using htaccess
[英]Wordpress Remove Slug from Custom Post
我的永久链接结构设置为: %category%/%postname%/
我想从我的自定义帖子中删除该子弹,发现以下解决方案:
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' );
但是,仅当我的永久链接设置为/%postname%/
有什么想法可以使它适用于: %category%/%postname%/
结构吗?
在您的function.php中添加以下代码并更新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' );
以下代码将起作用,但是您只需要记住,如果自定义帖子类型的子句与页面或帖子的子句相同,则冲突很容易发生...
首先,我们将从永久链接中删除该段:
function na_remove_slug( $post_link, $post, $leavename ) {
if ( 'events' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'na_remove_slug', 10, 3 );
仅仅去除弹头是不够的。 现在,您将获得404页面,因为WordPress只希望帖子和页面具有这种行为。 您还需要添加以下内容:
function na_parse_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( 'post', 'events', 'page' ) );
}
}
add_action( 'pre_get_posts', 'na_parse_request' );
只需将“事件”更改为自定义帖子类型,就可以了。 您可能需要刷新您的永久链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.