Filter WordPress Content by Taxonomy with a Dropdown

On content-heavy sites, custom taxonomies are often used to organize information. Sometimes we also need to filter content by taxonomy on the front end. For example, imagine a custom post type called “School” that is connected to a custom taxonomy called “State.” If we want to filter the school list by state, the approach below works well.

The function for taxonomy-based content filtering in WordPress

function state_taxonomy_dropdown( $taxonomy, $orderby = 'date', $order = 'DESC', $limit = '-1', $name, $show_option_all = null ) {
    $args = array(
        'orderby' => $orderby,
        'order' => $order,
        'number' => $limit,
    );
    $term_now = get_query_var('term');
    $terms = get_terms( $taxonomy, $args );
    $name = ( $name ) ? $name : $taxonomy;
    if ( $terms ) {

            printf( '' );
  }
}

The function parameters and how to use them

This function accepts several parameters so the dropdown can be adjusted as needed:

  • $taxonomy: the custom taxonomy slug used for filtering.
  • $orderby: the ordering method, defaulting to publish date.
  • $order: ascending or descending order, defaulting to descending.
  • $limit: the number of terms to display, defaulting to all.
  • $name: the name attribute used for the filter form, required.
  • $show_option_all: whether to show an “all” option, hidden by default.

For example, if you want to output a dropdown containing all states and use it as a filter condition, place code like the following into the custom post type archive or taxonomy archive template:

<?php state_taxonomy_dropdown( 'state', 'date', 'DESC', '5', 'state', '显示所有' ); ?>

That produces a taxonomy dropdown very similar to the category filter behavior many people already know from WordPress widgets.

Related Posts

Leave a Reply

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