WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Return all category id's from single post (3 posts)

  1. jakethebear
    Member
    Posted 1 year ago #

    this is something that should be stupidly easy, but i can't find a straight answer, and the documentation on 'wp get post categories' is pretty rubbish. i'm looking to get all the id's of all the categories assigned to a single post in order to use them as classes. any help much appreciated. thanks in advance.

  2. alchymyth
    The Sweeper & Moderator
    Posted 1 year ago #

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

    where exactly did you get stuck with that Codex chapter?

    what code have you tried?

    alternatively, consider using get_the_category() http://codex.wordpress.org/Function_Reference/get_the_category

  3. jakethebear
    Member
    Posted 1 year ago #

    get_the_category() worked perfectly, thank you. For some reason I couldn't get wp_get_post_categories() to work, no matter how I tried implementing it.

    If anyone else is looking to do the same thing and use a specific post's category ID's as classes, here's my code:

    <?php
    $categories = get_the_category();
    $separator = ' ';
    $classes = '';
    if($categories){
       foreach($categories as $category) {
          $classes .= 'cat-'.$category->term_id.$separator;
       }
    }
    ?>
    
    <div class="<?php echo trim($classes, $separator); ?>">
       DIV CONTENT
    </div>

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.