Monday, February 7, 2022

[FIXED] customize woocomerce product order random + featured wordpress

Issue

I would like to achieve a custom ordering for products in woocomerce. I would like to get first a few featured products, then all the others randomly.

Is it possible to modify it somehow, that products with same menu order id will shown in a random order, but lower menu order id will shown before a higher one.

Or select a specifiy order id for indicating random order.

I currently have this method for showing all the products in random order:


function custom_woocommerce_get_catalog_ordering_args( $args ) {
   $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
   
   
   if ( 'random_list' == $orderby_value ) {
       $args['orderby'] = 'rand';
       $args['order'] = '';
       $args['meta_key'] = '';
   }

   return $args;
}

add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );

function custom_woocommerce_catalog_orderby( $sortby ) {
   $sortby['random_list'] = 'Random';
   return $sortby;
}

Is it somehow possible to somehow make a new product order option and then customize it with wp queries, to give them the actual products I want to see.


Solution

I turns out that you can have multiple fields in the orderby field regarding to this post: Multiple order by in WooCommerce

So I made a custom ordering options, which is first ordering by the menu_order then rand. So I just have to give the same menu_order to each product which I want to show randomly.


function custom_woocommerce_get_catalog_ordering_args_2( $args ) {
  $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
  
  
  if ( 'featured_random_list' == $orderby_value ) {
      $args['orderby'] = 'menu_order rand';
      $args['order'] = 'ASC';
      $args['meta_key'] = '';
  }

  return $args;
}

add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby_2' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby_2' );

function custom_woocommerce_catalog_orderby_2( $sortby ) {
  $sortby['featured_random_list'] = 'Our order';
  return $sortby;
}


Answered By - Mátyás GrÅ‘ger

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.