Support

Account

Home Forums General Issues orderby multiple field values

Solving

orderby multiple field values

  • Hello all, I have a custom post type which I need to order in a specific order. These custom fields are Best Seller, and New, based on these values, it shows a tag on the post. New is not related to the post date just to make that clear. I want to query all the posts for this custom post type, but order them in the following order Best Seller, New, the rest of the posts.

    Here is what I have tried, but the order is wrong, I can’t figure out how to get this query to work and order the posts how I want.

    $args = array(
    	'post_type' => 'products',
    	'post_status'    => 'publish',
    	'showposts' => '-1',
    	'tax_query' => array(
    		array(
    			'taxonomy' => 'products_category',
    			'field'    => 'id',
    			'terms'    => $termId,
    		),
    	),
    	'paged'     => $paged,
    	'meta_query'    => array(
    		array(
    			'relation' => 'OR',
    			'best_seller' => array(
    				'key'       => 'best_seller',
    				'value' => 1,
    				'compare' => '>='
    			),
    			'new' => array(
    				'key'       => 'new',
    				'value' => 1,
    				'compare' => '>='
    			),
    			'others_best_seller' => array(
    				'key'       => 'best_seller',
    				'value' => 1,
    				'compare' => '<'
    			),
    			'others_new' => array(
    				'key'       => 'new',
    				'value' => 1,
    				'compare' => '<'
    			),
    		)
    	),
    	'orderby' => array(
    		'best_seller'  => 'DESC',
    		'new'     => 'DESC',
    		'others_best_seller'     => 'DESC',
    		'others_new'     => 'DESC',
    	)
    );
  • Ended up getting all the posts, created arrays for best seller, new, others, looped through each post and assigned to appropriate array, merged the arrays, then looped through the merged array to display the posts, works.

  • To do what you originally asked you need to use clauses for your meta_query. see ‘orderby’ with multiple ‘meta_key’s on this page https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters, it’s the 10th code snippet in the Order & Orderby Parameters section.

  • Just tried the approach suggested by John, works perfectly.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.