wordpress:How to get category slug and link(parent and child)

Published on:
Last updated:

This post is also available in: 日本語 (Japanese)

This post is about how to get parent/child category slug and link, and the sample code
The sample code below uses query_posts function to get a list of articles .
Then it writes that the category name of the article list, and the category slug and the link to the category are getted and displayed.
(Get child category slug when belonging to child category, get parent category slug when child category does not exist and belongs only to parent category)

By the way, in the sample code, the category name is described in CSS class.

<?php query_posts("post_type=post&posts_per_page=10"); ?>
<?php if(have_posts()): ?>
<ul>
<?php while(have_posts()):  the_post(); ?>
<?php
$cats = get_the_category();
$current_cat = '';
foreach ( $cats as $cat ) {
  if ( ! $current_cat || cat_is_ancestor_of( $current_cat, $cat ) ) { //Whether parent category or not
    $current_cat = $cat;
  }
}

$catname = $current_cat->cat_name; //get category name
$catslug = $current_cat->slug; //get category slug
$catid = $current_cat->cat_ID; //get category ID
?>
<li>
<span class="<?php echo $catslug; ?>"><a href="<?php echo get_category_link($catid) ?>"><?php echo $catname; ?></a></span><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php else: ?>
<p>There are currently no posts.</p>
<?php endif; ?>

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and follow me on LinkedIn.