Wordpress Woocommerce sort products differently pe

2019-08-11 19:17发布

I am working with wordpress and woocommerce. What I have been trying and search for the last days is a way to sort products per productcategory. Products in category 'cars' for instance must be sorted by price ASC. I have about 10 different categories with different sorting. I thought this code below would solve my problem, but it doest. I have tried multiple ways, but can't find the right one. My PHP knowledge is very limited, but learning everyday. Shoud I use case ? How would I accomplish this ? Or maybe it's just a other way of writing ? I hope someone can assist me. Thanks in advance.

Bas

add_filter('woocommerce_get_catalog_ordering_args','tk_woocommerce_catalog_orderbyb');
function tk_woocommerce_catalog_orderbyb( $args ) {
   $cat = get_the_terms( $product->ID, 'product_cat' );
   foreach ($cat as $categoria) {
      if($categoria->parent == 0) {
         $main_parent = $categoria->name;
      }
   }
   if($main_parent == 'Cars') {
      $args['orderby']  = 'meta_value_num';
      $args['order']    = 'ASC';
      $args['meta_key'] = '_price'; 
   }
   return $args;
}

1条回答
小情绪 Triste *
2楼-- · 2019-08-11 20:16

I know this is not a very clean solution, but it works. And with an 'else if' statement ( or with case ) I can use different sorting per product category.

add_filter('woocommerce_get_catalog_ordering_args', 'tk_woocommerce_catalog_orderbyb');
function tk_woocommerce_catalog_orderbyb($args) {
$urlb = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($urlb,'cars')) {
    $args['orderby']  = 'meta_value_num';
    $args['order']    = 'ASC';
    $args['meta_key'] = '_price'; 
    }
return $args;
}
查看更多
登录 后发表回答