Archived topic
How to Generate Category Links of Current Post
7 replies · Started by Joezer on March 23, 2022
Hello,
I am trying to make the categories of a current post show up with manual code as I am using my own post header area. My code is:
<?php
$category = get_the_category();
$first_category = $category[0];
echo sprintf( '%s', get_category_link( $first_category ), $first_category->name );
?>
The problem with this code is that it only works for posts with one category. If a post has multiple categories, it will only show the category that is closest to letter A. And not as Category A, Category B, Category C like what happens when using GP default settings.
Hi Joezer,
Here is something you may refer to:
<?php
$categories = get_the_category();
foreach ( $categories as $key=>$category ) {
echo sprintf( '%s', get_category_link( $category ), $category->name );
}
?>
Hope this helps! :)
The code works thanks, but I don't know how to add a separator, can you show me how? So by default it's a comma, would it be possible to change it into a dash?
I see. If that’s the case here is an example of an approach you may try to accomplish this.
<?php
$categories = get_the_category();
$myseparator = '<span> | </span>';
$count = 0;
foreach ( $categories as $key=>$category ) {
if ($count===0) {
echo '<a href="' . get_category_link( $category ) . '">' . $category->name . '</a>';
} else {
echo $myseparator;
echo '<a href="' . get_category_link( $category ) . '">' . $category->name . '</a>';
}
$count++;
}
?>
Kindly replace | with your preferred separator. You may also replace $category->name with get_category_link( $category ) if you wish or change the HTML structure completely if you prefer.
Edit: Here is something shorter that would also work:
<?php
echo strip_tags( get_the_term_list( get_the_ID(), 'category', '', ', ') );
?>
reference: https://developer.wordpress.org/reference/functions/get_the_terms/
Kindly use which you prefer.
Hope this helps! :)
Hello,
Sorry, I was AFK for the weekend and weren't able to try the codes out. Can you show me how to make this a clickable link?
echo strip_tags( get_the_term_list( get_the_ID(), 'category', '', ', ') );
I tried it out and it is only generating the text
Hi there,
you don't need the strip_tags - use this:
echo get_the_term_list( get_the_ID(), 'category', '', ', ');
Works now, I've also managed to change the separator using the codes provided. Many thanks, Fernando and David
Glad we could be of help