• Resolved oldmankit

    (@oldmankit)


    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;

Viewing 3 replies - 1 through 3 (of 3 total)
  • $category->slug

    $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> ';

    Thread Starter oldmankit

    (@oldmankit)

    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.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Quick code question: get the category nicename’ is closed to new replies.