• Resolved Slava Kuptsov

    (@slavakuptsov)


    Hi, I tried to change default sort to achieve sorting by 2 meta_keys. I want to have out of stock products at the end of products list:

    add_filter('woocommerce_get_catalog_ordering_args', 'custom_catalog_ordering_args');
    
    function custom_catalog_ordering_args($args) {
    	global $wp_query;
    
    	$orderby = $args['orderby'];
    	$order = $args['order'];
    
    	$args['order'] = '';
    	$args['meta_key'] = '_stock_status';
    	$args['orderby'] = array('meta_value' => 'ASC', $orderby => $order);
    
    	return $args;
    }

    But i does not work. Is there a possibility to do this?

    https://wordpress.org/plugins/woocommerce/

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author Mike Jolley (a11n)

    (@mikejolley)

    See the docs here https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

    I don’t think its possible. You can combine pairs of orderby args, but there are no examples for multiple meta.

    Thread Starter Slava Kuptsov

    (@slavakuptsov)

    Finally I found a solution. From WP 4.2 you can order by multiple meta keys:https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/
    If you want to push out of stock products to the end of products list:

    add_action( 'pre_get_posts', 'change_wp_query' );
    function change_wp_query($query) {
    	global $wp_query;
            if (is_shop() || is_product_category()) {
    			$orderby = get_query_var('orderby');
    			$order = get_query_var('order');
    			$meta_key = get_query_var('meta_key');
    
    			if ($meta_key == '') {
    				$wp_query->set( 'meta_key', '_stock_status' );
    				$wp_query->set( 'orderby', array( 'meta_value' => 'ASC', $orderby => $order) );
    			} else {
    				$wp_query->set( 'meta_query', array(
    					'relation' => 'AND',
    					'stock' => array(
    						'key' => '_stock_status',
    						'compare' => 'EXISTS'
    					),
    					'sorting_option' => array(
    						'key' => $meta_key,
    						'compare' => 'EXISTS',
    						'type' => 'NUMERIC'
    					)
    				) );
    				$wp_query->set( 'orderby', array( 'stock' => 'ASC', 'sorting_option' => $order) );
    			}
    
    			$wp_query->set( 'order', '' );
    		}

    Best wishes, Slava

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Sorting shop by 2 meta_keys’ is closed to new replies.