Orderby Custom Field then Post Title not working
-
Someone kindly helped me with some custom code for a business listing website I am building.
There are featured listings and standard listings. The ACF True/False field ‘business_featured_business’ is the way they are differentiated.
I want featured businesses to list first then standard listings and the businesses to be in alphabetical order of post title within that.
Because I am using front end forms to allow people to create their listing, the form for standard listings doesn’t have the ‘business_featured_business’ field in it. This results in no post meta entry being created when the form is submitted. (I can’t find a way to set the meta value to 0 automatically)
The problem is that the code I have for sorting on the archive page isn’t working. It successfully displays my featured businesses first – and seems to display those in alphabetical order. But the businesses that aren’t featured are sorting in the default WP descending post date order.
Can anyone help me to adjust the code below to get the sorting right i.e.
Featured
Business A
Business D
Standard
Business B
Business C
Many thanks in advance.add_action('pre_get_posts', function($query) { if ($query->is_post_type_archive('business-listings') && $query->is_main_query()) { $meta_query = array( 'relation' => 'OR', array( 'key' => 'business_featured_business', 'compare' => 'EXISTS', ), array( 'key' => 'business_featured_business', 'compare' => 'NOT EXISTS', ), ); $query->set('meta_query', $meta_query); $query->set('orderby', array('meta_value_num' => 'ASC', 'title' => 'ASC')); } });
- The topic ‘Orderby Custom Field then Post Title not working’ is closed to new replies.