daniel-w
7/15/2015 - 5:58 PM

Add filters for custom taxonomies in WordPress backend.

Add filters for custom taxonomies in WordPress backend.

//----------------------------------------------------------------------------------
// Taxonomy Filter For Backend
//----------------------------------------------------------------------------------

function filter_product_by_type()
{
    global $typenow;
    $post_type = 'product'; // change HERE
    $taxonomy = 'product-type'; // change HERE
    if ($typenow == $post_type) {
        $selected = isset($_GET[$taxonomy]) ? $_GET[$taxonomy] : '';
        $info_taxonomy = get_taxonomy($taxonomy);
        wp_dropdown_categories(array(
            'show_option_all' => __("Show All {$info_taxonomy->label}"),
            'taxonomy' => $taxonomy,
            'name' => $taxonomy,
            'orderby' => 'name',
            'selected' => $selected,
            'hierarchical'    =>  true,
            'depth'           =>  3,
            'show_count' => true,
            'hide_empty' => true,
        ));
    };
}

add_action('restrict_manage_posts', 'filter_product_by_type');

function convert_id_to_term_in_query($query)
{
    global $pagenow;
    $post_type = 'product'; // change HERE
    $taxonomy = 'product-type'; // change HERE
    $q_vars = &$query->query_vars;
    if ($pagenow == 'edit.php' && isset($q_vars['post_type']) && $q_vars['post_type'] == $post_type && isset($q_vars[$taxonomy]) && is_numeric($q_vars[$taxonomy]) && $q_vars[$taxonomy] != 0) {
        $term = get_term_by('id', $q_vars[$taxonomy], $taxonomy);
        $q_vars[$taxonomy] = $term->slug;
    }
}

add_filter('parse_query', 'convert_id_to_term_in_query');