我正在使用此解决方案从我的博客文章的网址中删除子类别: 从 WordPress 中博客文章和自定义文章类型的永久链接 URL 中删除子类别 slug
add_filter('post_link','custom_post_type_link',10,3);
function custom_post_type_link($permalink, $post, $leavename) {
if (!gettype($post) == 'post') {
return $permalink;
}
switch ($post->post_type) {
case 'post':
//$permalink = get_home_url() . '/' . $post->post_name . '/';
$cats = get_the_category($post->ID);
$subcats = array();
foreach( $cats as $cat ) {
$cat = get_category($cat->term_id);
if($cat->parent) { $subcats[] = sanitize_title($cat->name); }
}
if($subcats) {
foreach($subcats as $subcat) {
$subcat = $subcat.'/';
$permalink = str_replace($subcat, "", $permalink);
}
}
break;
}
return $permalink;}
工作正常,但代码仍然存在一些问题。
如果我有这样的网址:
www.myblog.com/parentcategory/nameofchildcategory/slugpost
我会得到这个:
www.myblog.com/parentcategory/slugpost
这正是我想要的。
但是如果我有这样的 URL:
www.myblog.com/parentcategory/nameofchildcategory/slugpost-with-nameofchildcategory
我会得到这个:
www.myblog.com/parentcategory/slugpost-with- (发送 slug 的末尾)
...以及本文的每个链接的 404 页面。
所以问题是,当子类别文本出现在 slug 的帖子中时,代码也会删除这部分 URL。
有人知道如何解决这个问题吗?
提前致谢!
我找到了这个解决方案,添加了两个功能。我不确定代码是否最优,但它运行完美。
add_filter('post_link','custom_post_type_link',10,3);
//function to see if URL ends with...
function endsWith($string, $endString) {
$len = strlen($endString);
if ($len == 0) {
return true;
}
return (substr($string, -$len) === $endString);
}
//function to replace only first match
function str_replace_first($from, $to, $content)
{
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $content, 1);
}
function custom_post_type_link($permalink, $post, $leavename) {
if (!gettype($post) == 'post') {
return $permalink;
}
switch ($post->post_type) {
case 'post':
//$permalink = get_home_url() . '/' . $post->post_name . '/';
$cats = get_the_category($post->ID);
$subcats = array();
foreach( $cats as $cat ) {
$cat = get_category($cat->term_id);
if($cat->parent) { $subcats[] = sanitize_title($cat->name); }
}
if($subcats) {
foreach($subcats as $subcat) {
$subcat = $subcat.'/';
//If URL ends with category name
if(endsWith($permalink,$subcat)){
//And if the category name appears more than once
if(substr_count($permalink,$subcat)>1){
// Remove only first match
$permalink = str_replace_first($subcat, "", $permalink);
}else{
//do nothing
}
}
// If URL does NOT end with category name
else{
$permalink = str_replace($subcat, "", $permalink);
}
}
}
break;
}
return $permalink;}
尝试界定线段的两端,例如:
foreach ($subcats as $subcat) {
$permalink = str_replace('/'.$subcat.'/', '/', $permalink);
}