WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Quick code question: get the category nicename (4 posts)

  1. oldmankit
    Member
    Posted 3 years ago #

    Hello,

    I found the following at the wordpress codex and it's really useful for my category archives page:

    <?php
    $args=array(
      'orderby' => 'name',
      'order' => 'ASC'
      );
    $categories=get_categories($args);
      foreach($categories as $category) {
        echo '<p>Category: <a>term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
        echo '<p> Description:'. $category->description . '</p>';
        echo '<p> Post Count: '. $category->count . '</p>';  }
    ?>

    Is there a way I can get the category nice name (slug?), not the whole link? I want to create custom div classes depending on the category. I'm not an expert. I use the following for normal blog posts, but I can't find a way to get this to work with the above code.

    $category =  get_the_category();
    	        $posttitle .= $category[0]->category_nicename;
  2. alchymyth
    The Sweeper & Moderator
    Posted 3 years ago #

    $category->slug

  3. Chip Bennett
    Theme Review Admin
    Posted 3 years ago #

    $category->category_nicename;

    You're inside a foreach loop, so you don't want to specify the array index, i.e. $category[0]. You just want to target $category.

    So, this won't work:

    $category[0]->category_nicename

    but this will:

    $category->category_nicename

    Take a look at your syntax in this line; it appears to be mal-formed:

    echo '<p>Category: <a>term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
  4. oldmankit
    Member
    Posted 3 years ago #

    Thank you both. Both solutions ($category->slug; and $category->category_nicename;) worked.

    I can see that the syntax in my original post is wrong. I just copied and pasted from here. Something happened which I don't understand...

    Thank you very much again.

Topic Closed

This topic has been closed to new replies.

About this Topic