wordpress - 删除自定义帖子类型 Slug 但如果有父级,请将其保留在 URL 中
问题描述
我注册了一个自定义帖子类型,将重写设置为 'rewrite' => array( 'with_front' => true )
,并使用以下方法从中删除了 slug:
function my_remove_slug( $post_link, $post, $leavename ) {
if ( 'content_hub' != $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', 'my_remove_slug', 10, 3 );
function my_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', 'content_hub', 'page' ) );
}
}
add_action( 'pre_get_posts', 'my_parse_request' );
这对于不包含父级的 URL 非常有效,但是它也会重写包含父级的 URls。
例如:
mydomain.com/parent-slug/child-slug
这将返回 404。
然而,没有 parent-slug 的相同 url 加载。
我需要对其进行更改,以便在 URL 中仍包含 parent-slug(如果存在)。
我试过这样的事情:
function my_remove_slug( $post_link, $post, $leavename ) {
if ( 'content_hub' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
$post_link = str_replace( '/' . $post->post_type . '/', '/' . $parent_slug . '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'my_remove_slug', 10, 3 );
但这会将网址返回为:
mydomains.com/parent-slug/parent-slug/child-slug
并且仍然显示404。
解决方案
推荐阅读
- javascript - 在 Typescript 的静态方法中访问类类型参数的解决方法
- shiny - Shiny 在渲染过程中生成的 CSS 和 Javascript 文件在哪里?
- python - 哪些版本的 TensorFlow 可以与哪些版本的 CUDA 配合使用
- python - matplotlib plt.Rectangle 的奇怪行为
- google-cloud-build - 在合并时部署,而不是在使用 Google Cloud Build 的拉取请求时部署
- java - 如何将空数组列表添加到 ListView?尝试在空对象引用上调用接口方法“int java.util.List.size()”
- laravel - laravel Policy 参数太少而无法运行
- machine-learning - Doc2Vec 与 Keras
- javascript - 相对于目标容器的拖放位置
- java - 扩展泛型类时遇到问题