最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

categories - How to fix get_the_category function returning incorrect slug?

programmeradmin1浏览0评论

So, I'm having an issue where using the get_the_category function is returning an incorrect slug. My code snippet is as so:

 <?php $category_detail=get_the_category($post->ID);
        foreach($category_detail as $cd){?>
        <li class="list-inline-item"><a href="<?php echo $cd->slug ?>"><?php echo $cd->cat_name; ?></a> 
   </li><?php } 

The issue is that the category slug doesn't reflect my site's permalink settings, and returns: "mysite/category-name" and not "mysite/category/category-name". I am not sure why the category permalink is being truncated, as the category pages work correctly, but this function is outputting them incorrectly, The slug in question here is for regular posts.

So, I'm having an issue where using the get_the_category function is returning an incorrect slug. My code snippet is as so:

 <?php $category_detail=get_the_category($post->ID);
        foreach($category_detail as $cd){?>
        <li class="list-inline-item"><a href="<?php echo $cd->slug ?>"><?php echo $cd->cat_name; ?></a> 
   </li><?php } 

The issue is that the category slug doesn't reflect my site's permalink settings, and returns: "mysite/category-name" and not "mysite/category/category-name". I am not sure why the category permalink is being truncated, as the category pages work correctly, but this function is outputting them incorrectly, The slug in question here is for regular posts.

Share Improve this question asked Nov 10, 2020 at 11:28 nizz0knizz0k 1198 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

The problem, as I could see it, is not with the get_the_category() function. Instead, it's the way you output the category archive link: href="<?php echo $cd->slug ?>" — you should instead use get_category_link() to get the correct URL of the category archive page. Example:

<a href="<?php echo esc_url( get_category_link( $cd ) ); ?>">
发布评论

评论列表(0)

  1. 暂无评论