- This topic has 7 replies, 3 voices, and was last updated 4 years ago by
David.
-
AuthorPosts
-
March 23, 2022 at 8:58 pm #2165372
Joezer
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.
March 23, 2022 at 9:36 pm #2165419Fernando Customer Support
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! 🙂
March 23, 2022 at 9:58 pm #2165423Joezer
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?
March 23, 2022 at 10:47 pm #2165448Fernando Customer Support
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->namewithget_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! 🙂
March 28, 2022 at 4:06 am #2169573Joezer
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
March 28, 2022 at 4:22 am #2169584David
StaffCustomer SupportHi there,
you don’t need the strip_tags – use this:
echo get_the_term_list( get_the_ID(), 'category', '', ', ');March 28, 2022 at 6:53 am #2169768Joezer
Works now, I’ve also managed to change the separator using the codes provided. Many thanks, Fernando and David
March 28, 2022 at 6:58 am #2169775David
StaffCustomer SupportGlad we could be of help
-
AuthorPosts
- You must be logged in to reply to this topic.