Archive for JavaScript

Category Drop-Down in WordPress

WordPress provides a template tag, wp_dropdown_categories, that inserts a drop-down list (the HTML <select> element) of categories, where the value of each item is the ID from the database. This works fine if you are not using rewrite rules (AKA “pretty links”) – you can construct a URL using the value (?cat=[number]). However, if you use any sort of rewrite rules, this does not work. I recently converted my personal site, which uses the Pool theme, to utilize a JavaScript array to assist with displaying category pages.

Here’s the code…

<?php
/**
* This creates a list of category links that can be used with a category dropdown
*/
$aCategories = get_all_category_ids();
$iMaxCat = 0;
foreach($aCategories as $iThisCat) {
    if ($iMaxCat < $iThisCat) {
        $iMaxCat = $iThisCat;
    }
}
$iMaxCat++;
?><div style="text-align:center;">
    <form name="categoryform" action="" style="text-align:center;">
    <script type="text/javascript">
        var aLink = new Array(<?php echo($iMaxCat); ?>);
<?php
foreach($aCategories as $iThisCat) {
    echo("aLink[$iThisCat] = "" . get_category_link($iThisCat) . "";\n");
} ?>        function goCat() {
            window.location =
                aLink[document.getElementById('cat')[document.getElementById('cat').selectedIndex].value];
        }
    </script>
    <?php wp_dropdown_categories('class=sidebardropdown&orderby=name&show_count=1&hierarchical=1'); ?>
    <br />
    <button class="sidebarbutton" type="button" style="margin-top:5px;" onclick="goCat();">View Category</button>
    </form>
</div>

This works for both “pretty” and standard links, as it uses the template tag get_category_link to specify the link.

Comments