WordPress文章固定链接去掉父级或子分类目录方法

在 WordPress 网站中,如果 固定链接 使用/%category%/ 的时候,发布的文章链接会详细展示父级和所有子分类目录,导致文章 URL 链接会变得很长,且很混乱,不利于SEO。

WordPress文章固定链接去掉父级或子分类目录方法WordPress文章固定链接去掉父级或子分类目录方法

举个例子:

科技号 顶级栏目有 苹果(apple),里面有分类了 资讯(zixun)子栏目,默认情况下,该子分类的文章链接为:

https://www.zmtc.com/apple/news/id.html

如果资讯里面还有子分类,那么文章链接还会更长。

如果我们要优化固定链接的文章网址,希望链接变短一些该如何操作呢?

目前,主要有两种思路,一种是去掉 父分类,链接就变成了这样:

https://www.zmtc.com/news/id.html(方式一)

另外一种是去掉 子分类,,链接就变成了这样:’

https://www.zmtc.com/apple/id.html(方式二)

WordPress文章固定链接去掉父级或子分类目录如何实现呢?

其实也很简单,只需要修改主题 functions.php 文件即可实现,方法如下。

方式一:去掉父级分类目录

// pcxun.com去掉父级分类目录
add_filter( ‘post_link’, ‘dahuzi_remove_parent_cats_from_link’, 10, 3 );
function dahuzi_remove_parent_cats_from_link( $permalink, $post, $leavename )
{
$cats = get_the_category( $post->ID );
if ( $cats ) {
usort( $cats, ‘_usort_terms_by_ID’ );
$category = $cats[0]->slug;
if ( $parent = $cats[0]->parent ) {
$parentcats = get_category_parents( $parent, false, ‘/’, true );
$permalink = str_replace( $parentcats, ”, $permalink );
}
}
return $permalink;
}

将以上代码添加到 functions.php 文件即可。

方式二:去掉子分类目录

// pcxun.com去掉后子分类目录
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($cat->parent) { $subcats[] = $cat->slug;}}
if($subcats) {
foreach($subcats as $subcat) {
$subcat = $subcat.’/’;
$permalink = str_replace($subcat, “”, $permalink);}}
break;}
return $permalink;}

将以上代码添加到 functions.php 文件即可。

以上就是WordPress文章固定链接去掉父级或子分类目录方法,如果你的Wordpress网站固定链接使用了/%category%/ ,希望文章链接尽量短一些的话,可以通过两种方式进行优化哦。

文章来自互联网,不代表电脑知识网立场。发布者:达瓦里氏,转转请注明出处:https://www.pcxun.com/n/41151.html

(0)
上一篇 2024-01-16 08:30
下一篇 2024-01-16 08:30