The code below is suppose to display all posts with "featured_listing" meta key above all of the standard posts.
When the below code is in the functions.php, it hides all posts without "featured_listing" meta. Instead of showing them below the featured listings.
function custom_special_sort( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
// if is this the main query and is this post type of business
if ( (is_post_type_archive('business') ) || (is_tax ('location') ) ) {
// order results by the meta_key 'featured_listing'
$query->set( 'meta_key', 'featured_listing' );
$query->set( 'orderby', 'featured_listing' );
$query->set( 'order', 'DESC' );
}
}
add_action( 'pre_get_posts', 'custom_special_sort' );
I thought I had solved the problem with the following code :
add_filter('posts_join', 'custom_special_sort_join' );
function custom_special_sort_join($wp_join)
{
if(is_post_type_archive('business') || is_tax ('location') || (is_admin() && $_GET['post_type'] == 'business')) {
global $wpdb;
$wp_join .= " LEFT JOIN (
SELECT post_id, meta_value as date_due
FROM $wpdb->postmeta
WHERE meta_key = 'featured_listing' ) AS DD
ON $wpdb->posts.ID = DD.post_id ";
}
return ($wp_join);
}
add_filter('posts_orderby', 'custom_special_sort_order' );
function custom_special_sort_order( $orderby )
{
if(is_post_type_archive('business') || is_tax ('location') || (is_admin() && $_GET['post_type'] == 'business')) {
$orderby = " STR_TO_DATE(DD.date_due,'%m/%d/%Y') DESC ";
}
return $orderby;
}
but upon adding more posts featured_listings I realised it wasn't sorting the post_meta values at all.
Is it because the post_meta "featured_listing" is on every post regardless of the value being empty or filled ? I want to order based on that post_meta being filled with "featured_listing", If empty sort normally.
I've now gone through so many different posts, I feel like im probably looking right at the solution but have gone blind to it.