简体   繁体   中英

Wordpress Woocommerce sort products differently per category

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;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM