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

  1. lisasy
    Posted 3 years 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:

    // 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?

    $category = get_the_category();
    $cat_=name =  $category[0]->cat_name;
  2. Michael
    Forum Moderator
    Posted 3 years ago #


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


  3. lisasy
    Posted 3 years ago #

    That works perfectly. Thank you so much!!!

  4. J
    Posted 3 years ago #

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


Topic Closed

This topic has been closed to new replies.

About this Topic