php - 从分层自定义帖子类型中删除基本 slug
问题描述
干杯,
出于 SEO 原因,我尝试删除自定义分层服务帖子类型的基本 slug(示例名称:“custom-service”)。这些方法称为 SEO 筒仓。我尝试了不同的方法来获得以下 url 结果。
它不应该看起来如何:
https://foo.bar/custom-service/seo-agency/
https://foo.bar/custom-service/seo-agency/seo-workshop/
https://foo.bar/custom-service/foobar-agency/
https://foo.bar/custom-service/foobar-agency/foobar-workshop/
它应该看起来如何:
https://foo.bar/seo-agency/
https://foo.bar/seo-agency/seo-workshop/
https://foo.bar/foobar-agency/
https://foo.bar/foobar-agency/foobar-workshop/
我使用以下教程来实现这些结构:
- https://wordpress.stackexchange.com/questions/114723/removing-base-slug-from-hierarchical-custom-post-type
- https://kellenmace.com/remove-custom-post-type-slug-from-permalinks/
有一些人有同样的问题:
- 删除分层自定义帖子类型的永久链接中的基本 slug
- https://wordpress.stackexchange.com/questions/159950/remove-base-slug-from-hierarchical-custom-post-type?rq=1
起初,我已经实现了 Matthew Boynes 的第一个教程的解决方案。一切正常,除了我的分页。如果我使用这些解决方案,我的分页将停止工作。函数中的以下代码可能add_rewrites()
会破坏分页:
add_permastruct( 'custom-service', "%custom-service%", array(
'ep_mask' => EP_PERMALINK
));
你不能调用我博客的页面。以下网址停止工作:
https://foo.bar/blog/page/2
https://foo.bar/cpt/page/2
在我的第二次尝试中,我删除了 Matthew Boynes 代码。在其存档中没有分页的博客是没有用的。然后我实施了来自“kellenmace.com”的解决方案。要使代码适用于分层帖子类型,您必须修改教程过滤器功能post_type_link
:
function remove_custom_service_slug( $post_link, $post ) {
if ( 'custom-service' === $post->post_type && 'publish' === $post->post_status ) {
if( $post->post_parent ) {
$parent = get_post($post->post_parent);
$post_link = str_replace( '/' . $post->post_type . '/' . $parent->post_name . '/', '/', $post_link );
} else {
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
}
}
return $post_link;
}
add_filter( 'post_type_link', 'remove_custom_service_slug', 10, 2 );
但是有一个大问题。它删除了基本 slug和父服务 slug:
https://foo.bar/seo-agency/
https://foo.bar/seo-workshop/
它有点令人沮丧。也许有人有删除分层帖子类型的基本 slug 的经验,并且对我的项目有很好的提示。
如果您有任何问题,或者您想了解更多信息或代码,请随时与我联系。
感谢您阅读我的问题!
解决方案
将函数更改为此以考虑所有情况:
试试这个代码,
function change_slug_struct( $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', 'single-link', 'page' ) );
} elseif ( ! empty( $query->query['pagename'] ) && false === strpos( $query->query['pagename'], '/' ) ) {
$query->set( 'post_type', array( 'post', 'single-link', 'page' ) );
// We also need to set the name query var since redirect_guess_404_permalink() relies on it.
$query->set( 'name', $query->query['pagename'] );
}
}
add_action( 'pre_get_posts', 'change_slug_struct' );
推荐阅读
- python - Scrapy FormRequest 参数不起作用但显示所有结果
- arrays - 如何在 Ruby 中将数字与数组相加?
- javascript - 如何按索引从文件输入(多个)中删除文件
- hyperledger-fabric - hyperledger-fabric 可以在不进入docker容器的情况下获取peer节点运行状态吗?
- css - 如何编写css选择器以在给定元素之前选择元素
- json - 在数据框列中切片 JSON 的一部分
- awk - 如何修改 sed awk 命令以使用相对路径
- vue.js - 如何在文本框内放置占位符文本
- amazon-rds - 为什么我不能使用 rds connector mule 4 for aurora 创建新的数据库集群
- c# - 如何在 xamarin Forms 中创建弹出视图