Sorting Woocommerce ASC and DESC based on category

I am trying to sort products into categories.

If Product Category A and Subcategories Sort ASC

Otherwise, if the category is B categories and subcategories sort DESC.

In .php functions

add_filter('woocommerce_get_catalog_ordering_args', 'am_woocommerce_catalog_orderby');
function am_woocommerce_catalog_orderby( $args ) {

$args['meta_key'] = 'countdown_date';

$args['orderby'] = 'meta_value';

// need an if statement here to switch the order

$args['order'] = 'DESC';         

return $args;
}

      

+3


source to share


1 answer


You can use the following code to solve your goal,

   add_filter('woocommerce_get_catalog_ordering_args','wdm_change_ordering',10,1);

   function wdm_change_ordering($args)
   { 
      if(is_product_category())
      {
          global $wp_query;
          $cat = $wp_query->get_queried_object();

          $category_A_term_id = 53;
          $category_B_term_id = 2;

          if(!empty($cat) && ($cat->term_id === $category_A_term_id || $cat->parent === $category_A_term_id))
        {
           $args['order'] = 'ASC';
        }
        elseif(!empty($cat) && ($cat->term_id === $category_B_term_id || $cat->parent === $category_B_term_id))
       {
          $args['order'] = 'DESC';
       }
  }

   return $args;   

      

}

Remember to change the values ​​of the $ category_A_term_id and $ category_B_term_id variables for the corresponding category IDs.



Above code will be checked if the current is a category archive page, and if so, category "A" or child of category "A", the change order is the same for category "B".

Alternatively you can also use the following WooCommerce condition,

 is_product_category( array( 'shirts', 'games' ) )

      

but all categories must be listed here.

+2


source







All Articles