Get Categories For Current Post

I wanted a func­tion that returned the cat­e­gories asso­ci­ated with the cur­rent post to save screen real estate. I wanted it to be a drop-down with a JavaScript onchange, but I couldn’t find it any­where. After some hack­ing I finally worked out a func­tion. Place the fol­low­ing code in your cur­rent theme’s functions.php file (if you don’t have one then cre­ate 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>";
}

Any­where you want this to show up put this func­tion in the loop or a sin­gle post page.

<?php drop_cats(); ?>

No Comments

Got Something to Say?

(Required)
(Required)