How can I echo the current post's category nicename inside main loop.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

 echo <div class="btn category-nicename"> 

 <?php endwhile; else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

I want to echo the category nicename inside div tag as a class and then want to target the css

Any suggestions?

  • In which template do you want to use this – Pieter Goosen Aug 9 '14 at 7:41
  • In category template – Hujjat Khan Aug 9 '14 at 9:10
  • OK will post revised code now – Pieter Goosen Aug 9 '14 at 9:11

You can use get_the_category inside the loop to get the category/ies a post is assigned to. To get a list of available member variables available, see get_categories.

I would suggest to target the first category only, which will also be the parent category if the post is assigned to only one parent and some of the parent's child categories. Here is an example to get the first category assigned to a post's nicename

$category = get_the_category(); 
$post_cat = $category[0]->category_nicename;

You can now use $post_cat as your class. Just remember to add this code before this line

echo <div class="btn category-nicename"> 

Just a word of advice here, do not abuse echo. Use php tags where necessary to avoid using the unnecessary use of echo. BTW, your syntax is wrong

echo <div class="btn category-nicename">

should be

echo '<div class="btn category-nicename">';

if you are going to use echo


From your comment above ^^, you need to get the current category's nice name. You can get the current category with get_query_var( 'cat') and from that you can get the nice name

$category = get_query_var( 'cat' );
$post_cat = $category->category_nicename;

As above, just use $post_cat in your class. I hope this answers your question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.