WooCommerce product filter for an attribute in the backend

Viewed 229

I want to have a filter for an attribute "brand" in the WooCommerce products section in the backend.

I am using the following code:

function custom_woocommerce_product_filters( $output ) {
    global $wp_query;
    
    $output .= wc_product_dropdown_categories(
                    array(
                            'show_option_none' => 'Filter by brand',
                            'taxonomy' => 'pa_brand',
                            'name' => 'pa_brand',
                            'selected' => isset( $wp_query->query_vars['pa_brand'] ) ? $wp_query->query_vars['pa_brand'] : ''
                        )
                    );
        
    return $output;
}
add_filter( 'woocommerce_product_filters', 'custom_woocommerce_product_filters' );

This code displays the dropdown list for the filter with all brands inside it, but clicking on "Filter" does not return the filtered products. It simply shows all the products.

Can someone help please?

Thanks

1 Answers

I recently discovered that you have to actually filter the results using the pre_get_posts() filter, having the dropdown alone is not enough. What I was able to come up with after searching similar questions on stackoverflow:

// Filter woocommerce admin products by artist
function apply_artist_custom_product_filters( $query ) {

global $pagenow;

// Ensure it is an edit.php admin page, the filter exists and has a value, and that it's the products page
if ( $query->is_admin && $pagenow == 'edit.php' && isset( $_GET['pa_artist'] ) && $_GET['pa_artist'] != '' && $_GET['post_type'] == 'product' ) {

  // Create meta query array and add to WP_Query
  $meta_key_query = array(
    array(
      'taxonomy'     => 'pa_artist',
      'field' => 'slug',
      'terms'   => esc_attr( $_GET['pa_artist'] ),
      'operator' => 'IN',
    )
  );
  $query->set( 'tax_query', $meta_key_query );

}
}
    
add_action( 'pre_get_posts', 'apply_artist_custom_product_filters' );

The snippet that did most of the work is found here:WooCommerce: Adding a custom filter to the Product Admin area. I only changed the meta query to be a tax query. Not sure if it's the best way to do it, but it works for me. What I can't figure out is the "selected" part of the wc_product_dropdown_categories, for me when I select an artist and hit filter, the filter works but it doesn't save the selection.

Related