Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative way to orderby grouped product child since filter `woocommerce_grouped_children_args` was removed from WooCommerce 3

In Wordpress Woocommerce I have created a grouped product, with lots of sub products (children) in it. I tried searching everywhere, but I can not find a working solution how to orderby them by either SKU or product name. It seems that it's orderby is generated by "Menu Order" only. Although as I have 30+ sub products in these multiple grouped products, it would be extremely time wasting to order them by Menu Order value.

I tried the following code, but it seems that it worked in WC 2.5, but not 3.0+ .

add_filter( 'woocommerce_grouped_children_args', 
'so_22661392_grouped_children_args' );

function so_22661392_grouped_children_args( $args ){

 $args['meta_key'] = 'sku';
 $args['orderby'] = 'meta_value';
 $args['order'] = 'ASC'; 
 return $args;

 }

I also searched Google for explanations but could not find any. I tried to clear transients, this doesn't work as well:

  WooCommerce>System Status>Tools>Clear Transients

The grouped product can be seen on https://plastmet.ee/uus/toode/umartoru-kork-zzo-pealekaiv/ . The html table should match the children below, but it does not. SKU for children is "563/9005", "567/9005" etc..

Any help would be greatly appreciated!

like image 646
Masqtto Avatar asked Jun 19 '17 18:06

Masqtto


1 Answers

Hopefully I understand the problem correctly:

If we have overriden the template file single-product/add-to-cart/grouped.php, then we could use e.g.:

if( $grouped_products )
    usort( $grouped_products, 'wc_products_array_orderby_title' );

to sort the grouped products by title, instead of the default menu ordering.

We could also unregister:

add_action( 'woocommerce_grouped_add_to_cart', 'woocommerce_grouped_add_to_cart', 30 );

with a custom callback instead.

As a last resort one could override the woocommerce_grouped_add_to_cart() function, e.g. within a plugin, to change the menu ordering.

It's defined as:

if ( ! function_exists( 'woocommerce_grouped_add_to_cart' ) ) {

   function woocommerce_grouped_add_to_cart() {
       global $product;

       $products = array_filter( array_map( 'wc_get_product', $product->get_children() ) );

       if ( $products ) {
            usort( $products, 'wc_products_array_orderby_menu_order' );

       wc_get_template( 'single-product/add-to-cart/grouped.php', array(
           'grouped_product'    => $product,
           'grouped_products'   => $products,
           'quantites_required' => false,
       ) );
    }
  }
}

where one could e.g. use wc_products_array_orderby_title instead.

like image 79
birgire Avatar answered Nov 15 '22 12:11

birgire