Skip to content

Instantly share code, notes, and snippets.

@mattsteele
Last active August 29, 2015 14:27
Show Gist options
  • Save mattsteele/9328ba6e6a68c5033180 to your computer and use it in GitHub Desktop.
Save mattsteele/9328ba6e6a68c5033180 to your computer and use it in GitHub Desktop.
Filter posts by category
<div class="styled-select">
<?php $args = array(
'show_option_none' => __( 'Filter Blog By Category' ),
'orderby' => 'name',
'exclude' => 1,
); ?>
<?php wp_dropdown_categories( $args ); ?>
<script type="text/javascript">
var dropdown = document.getElementById("cat");
dropdown.addEventListener('change', function() {
if (dropdown.options[dropdown.selectedIndex].value > 0 )
{
location.href = "<?php echo esc_url( home_url( '/' ) ); ?>?cat="+dropdown.options[dropdown.selectedIndex].value;
}
});
</script>
</div> <!--/ styled-select -->
@cfree
Copy link

cfree commented Aug 19, 2015

If IE9+, another approach would be to use the addEventListener() to allow for an unlimited number of onchange() events and to prevent the onchange() from being overwritten down the line:

var dropdown = document.getElementById("cat");

dropdown.addEventListener('change', function() {
    if (dropdown.options[dropdown.selectedIndex].value > 0 ) {
        location.href = "<?php echo esc_url( home_url( '/' ) ); ?>?cat="+dropdown.options[dropdown.selectedIndex].value;
    }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment