php - Wordpress 从自定义帖子中删除 Slug
问题描述
我的永久链接结构设置为:%category%/%postname%/
我想从我的自定义帖子中删除 slug,我找到了以下解决方案:
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 中添加以下代码并更新您的 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' );
推荐阅读
- python - Python RegEx 查找接近(之前和/或之后)特定单词的数值
- quanteda - 如何在 ac() 函数中添加带有单词的文件。量子
- amazon-web-services - 限制对我的 S3 存储桶的读写访问
- django - 未调用 Django REST Framework 字段序列化程序验证
- r - 绘制等值线图时出错
- go - 不能在字段值中使用提供者(类型 *[]versioner.ProviderResponse)作为类型 []*versioner.ProviderResponse
- node.js - 用passportjs认证后没有人要求回答
- php - 如何仅使用没有 ajax/jquery 的 php 创建依赖下拉列表
- python - 带有 git 的虚拟环境
- conceptual - 组织函数——你在哪里测试函数的参数?