WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Getting category slug from posts in the loop (4 posts)

  1. lisasy
    Member
    Posted 1 year ago #

    Hello! I am trying to figure out a way to output the category slugs for each of the posts in the loop.

    My general loop looks like this:

    <?php
    // The Query
    $the_query = new WP_Query($args);
    
    // The Loop
    while ( $the_query->have_posts() ) : $the_query->the_post();?>

    and I am trying to put each post in between <li>. I want to give each post a class within the <li> tag that consists of their category slugs (this is for JQuery purposes).
    I found this in a tutorial, but it doesn't work for me:

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

    I think I have to modify something like this, but I'm not sure. help?

    <?php
    $category = get_the_category();
    $cat_=name =  $category[0]->cat_name;
    ?>
  2. alchymyth
    The Sweeper & Moderator
    Posted 1 year ago #

    try:

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

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

  3. lisasy
    Member
    Posted 1 year ago #

    That works perfectly. Thank you so much!!!

  4. J
    Member
    Posted 1 year ago #

    From the 10 solutions i browsed through and tried, the was the simplest and the only one that worked.

    THANK YOU

Topic Closed

This topic has been closed to new replies.

About this Topic