Skip to content

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(); ?>
Published inTutorialsWordPress


  1. MissStack

    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 *