How to fix get_the_category function returning incorrect slug?

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.com/category-name" and not "mysite.com/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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 ) ); ?>">


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x