I'm not sure if im going about this the right way or not, seems to be alot of people doing this, but with completely different ways of doing it from queries in templates to functions so im not sure which route to go down.
I have a custom post type (business) which has featured posts, Each of these posts have a "featured_listing" post_meta which is either EMPTY or "featured-listing" value** attached to the post. I'd like to display the posts which do not have an empty post_meta value above all other posts in search results and categories.
**Note the - rather than _ for the value.
This is what I thought might work, but I'm starting to think I'm barking up the wrong tree.
// Order posts by meta data
function custom_special_sort( $query ) {
//is this the main query and is this post type of post
if ( $query->is_main_query() && $query->is_post_type( 'business' ) ) {
//Do a meta query
$query->get_post_meta(get_the_ID(), "featured_listing", TRUE);
//sort by a meta value
$query->set( 'orderby', 'featured_listing' );
$query->set( 'order', 'ASC' );
}
}
add_action( 'pre_get_posts', 'custom_special_sort' );
I've also just tried to do it slightly differently, below. But could do with some guidance as to why its not working or if im even doing it correctly:
function custom_special_sort( $query ) {
// Check this is main query and other conditionals as needed
if ( $query->is_main_query() && $query->is_post_type( 'business' ) ) {
$query->set(
'meta_query',
array(
array(
'key' => 'featured_listing',
'value' => 'featured-listing',
'orderby' => 'featured_listing',
'order' => 'DESC'
)
)
);
}
}
add_action( 'pre_get_posts' , 'custom_special_sort' );