Search code examples
phpwordpresswoocommercewp-admin

Add a custom taxonomy filter after product category filter in Woocommerce Admin products list


In my woocommerce storefront child theme, I have added several taxonomies. Now I would like to add a few category filters for those custom taxonomies. I have added such a filter using this code (credit: Rodolfo Melogli)

add_filter( 'woocommerce_product_filters', 'admin_filter_products_by_din' );
function admin_filter_products_by_din( $output ) {

  global $wp_query;

  $output .= wc_product_dropdown_categories( array(
    'show_option_all' => 'All DIN/ISO/ANSI',
    'taxonomy' => 'din-iso-ansi',
    'name' => 'din-iso-ansi',
    'order' => 'ASC',
    'tab_index' => '2',
    'selected' => isset( $wp_query->query_vars['din-iso-ansi'] ) ? $wp_query->query_vars['din-iso-ansi'] : '',
  ) );

  return $output;
}

The new category filter displays, but now I want the placement of my new taxonomy filter (DIN/ISO/ANSI) to go after the Product Categories filter.

product admin:

product admin


Solution

  • I figured this out with a lot of help from LoicTheAztec, essentially using most of his code, but it appears that we cannot substitute wp_dropdown_categories for wc_product_dropdown_categories so easily. After reviewing the function make-up of wc_product_dropdown_categories, I implemented another way to avoid having this function echo out the results by way of a little php.

    add_filter( 'woocommerce_product_filters', 'admin_filter_products_by_din' );
    function admin_filter_products_by_din( $output ) {
    
        global $wp_query;
    
        $taxonomy  = 'din-iso-ansi';
        $selected      = isset( $wp_query->query_vars[$taxonomy] ) ? $wp_query->query_vars[$taxonomy] : '';
        $info_taxonomy = get_taxonomy($taxonomy);
    
        ob_start(); // buffer the result of wc_product_dropdown_categories silently
        wc_product_dropdown_categories( array(
            'show_option_none' => __("Select a {$info_taxonomy->label}"), // changed
            'taxonomy'         => $taxonomy,
            'name'             => $taxonomy,
            //'echo'             => false, // <== Needed for in filter hook
            'tab_index'        => '2',
            'selected'         => $selected,
            'show_count'       => true,
            'hide_empty'       => true,
        ));
        $custom_dropdown = ob_get_clean();
    
    
        $before = '<select name="product_type"'; //
    
        $output = str_replace( $before, $custom_dropdown . $before, $output );
    
        return $output;
    }