Get Categories For Current Post

I wanted a function that returned the categories associated with the current post to save screen real estate. I wanted it to be a drop-down with a JavaScript onchange, but I couldn’t find it anywhere. After some hacking I finally worked out a function. Place the following code in your current theme’s functions.php file (if you don’t have one then create it).

function drop_cats() {
    echo "<select onChange=\"document.location.href=this.options[this.selectedIndex].value;\">";
    echo "<option>Categories</option>\n";
    foreach (get_the_category() as $cat)
      echo "<option value=\"";
      echo get_category_link($cat->cat_ID);      
      echo "\">" . $cat->cat_name . "</option>\n";
    echo "</select>";

Anywhere you want this to show up put this function in the loop or a single post page.

<?php drop_cats(); ?>

2 Responses

  1. Salem November 1, 2010 / 9:34 am

    thanks it’s work

  2. MissStack March 6, 2012 / 5:25 pm

    Thanks! I have spent lots of hours looking for this solution! And it worked.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>