0

I want to output the different categories assigned to a post. Let'say for example that a post has three categories:

  • Downloads
  • Games
  • Video

Previously I have used <?php echo get_the_category_list(); ?> But this wraps the <a> in a <span> instead of wrapping the <span> in a* <a>...

I want to list the categories like this:

<a href="the_URL_of_the_category_downloads">
    <span class="the_name_of_the_category_downloads">the_name_of_the_category_downloads</span>
</a>

<a href="the_URL_of_the_category_games">
    <span class="the_name_of_the_category_downloads">the_name_of_the_category_games</span>
</a>

<a href="the_URL_of_the_category_videos">
    <span class="the_name_of_the_category_downloads">the_name_of_the_category_videos</span>
</a>

I am not sure how I can get this to work with php as I have very limited knowledge of PHP in general.

2 Answers 2

0

You can use get_the_category( ) instead.

Example:

$categories = get_the_category();
foreach( $categories as $category) {
    $name = $category->name;
    $category_link = get_category_link( $category->term_id );

    echo "<a href='$category_link'>
            <span class=" . esc_attr( $name) . "></span>
         </a>";
}
5
  • There must be something wrong in your code. This gives me an error...
    – Arete
    Commented Dec 16, 2016 at 15:03
  • Hello @Arete, forgot to add a semicolon after the return statement. It's been corrected now.
    – Tunji
    Commented Dec 16, 2016 at 16:34
  • Still breaks my theme structure..
    – Arete
    Commented Dec 16, 2016 at 19:43
  • @Arete Looking at your code I guess echo should be used instead of return. I changed that.
    – JHoffmann
    Commented Dec 16, 2016 at 19:57
  • @Arete You're meant to sanitize user input and escape output, not the other way around.
    – Tunji
    Commented Dec 18, 2016 at 10:14
1

In the above 'answer', the last line which prints the category name is not actually doing so.

It should look like this:

$categories = get_the_category();
foreach( $categories as $category) {
    $name = $category->name;
    $category_link = get_category_link( $category->term_id );

    echo "<a href='$category_link'>
            <span class=" . esc_attr( $name) . ">" . esc_attr( $name) . "</span>
         </a>";
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.