Support

Account

Home Forums Front-end Issues Sort by custom field and publish date

Solved

Sort by custom field and publish date

  • Hello,

    I have a custom post type for “customer_reviews”. The post type contains an ACF field (True/False) for “featured” so that any review can be marked as a featured review. What i’m trying to do is to always display featured reviews at the top of a list of reviews, while the rest are shown ordered by date (post date). Currently, i can get the featured reviews to show at the top, but the rest of the reviews seem to be in random date order. Here are the arguments i’m currently using for the query:

    $review_args = array (
    'post_type' => 'customer_reviews',
    	'posts_per_page' => 20,
    	'post_status' => 'publish',
    	'meta_key' => 'featured',
    	'orderby' => 'meta_value_num',
    	'order' => 'DESC',
    	'fields' => 'ids'
    );

    What i can’t figure out is how to sort by both the “featured” custom field and the post date so that i’ll have featured reviews at the top of the list and then rest of the reviews from newest to oldest. I’ve been researching this for quite a while and can only find information related to sorting by a custom field, not by both.

    Thanks in advance for the help!

  • What you need to do is add meta_query clauses and order by the featured value and then the publish date. For more on meta_query clauses see this https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/

  • Thank you John, this solved my problem. I’m posting the updated code here for others to see. What i did is make the feature part of my meta_query and declare an index for “feature_clause” that just checks to see if the field exists. Then i added that to the “orderby” array including “date”, so both are sorted together. Here’s the updated query:

    $review_args = array ( 
    	'post_type' => 'customer_reviews',
    	'posts_per_page' => 20,
    	'post_status' => 'publish',
    
    	'meta_query' => array( 
    		'relation' => 'AND',
    		'feature_clause' => array(
    			'key' => 'featured',
    			'compare' => 'EXISTS',
    		),
    	),
    
    	'orderby' => array(
    		'featured' => 'DESC',
    		'date' => 'DESC',
    	),
    
    	'fields' => 'ids' 
    );
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.