Forums

List all post categories to be used as class names in template (6 posts)

  1. brettlewis
    Member
    Posted 1 year ago #

    I need to find the correct tag to use to list all the category names (from within a loop) to be used in as a class name.
    For example, I have a post under the categories "news" and "blog"

    I need to output in my loop code to look like this

    <div class="news blog"></div>

    I have been able to list a single category, but I need help getting a tag that will list all categories of the post, with a space between each.

    Thank you

  2. WP Hosting Australia
    Member
    Posted 1 year ago #

    Does this help?

    Posted in <?php the_category(', ') ?>

  3. alchymyth
    The Sweeper
    Posted 1 year ago #

    either look into post_class() http://codex.wordpress.org/Function_Reference/post_class

    or use:

    http://codex.wordpress.org/Function_Reference/get_the_category

    <div class="<?php foreach((get_the_category()) as $category) {
        echo  $category->slug . ' ';
    } ?>">
  4. brettlewis
    Member
    Posted 1 year ago #

    This one worked great! Thank you very much.

    <div class="<?php foreach((get_the_category()) as $category) {
        echo  $category->slug . ' ';
    } ?>">

    This one seems to post the link which is a problem when trying to use the category names as classes. Thank you though for the suggestion!
    <?php the_category(', ') ?>

  5. brettlewis
    Member
    Posted 1 year ago #

    I have a question for this one"

    <div class="<?php foreach((get_the_category()) as $category) {
        echo  $category->slug . ' ';
    } ?>">

    it works, but it outpust a space after every category so it makes the div look like this

    <div class="about home "></div>

    I know it shouldn't matter much, but is there a way to make it not space after the final category. I know that within the tags to list categories as links there is a way to specify what is in-between each output instead of what is after each output.

  6. alchymyth
    The Sweeper
    Posted 1 year ago #

    you are right - it does not matter for the html code;

    however, here you go:

    <div class="<?php foreach((get_the_category()) as $category) {
        echo  $sep . $category->slug; $sep = ' ';
    } ?>">

    when the foreach starts, the $sep is not initialized, i.e. empty. then it gets filled with the space character.

Topic Closed

This topic has been closed to new replies.

About this Topic