Skip to main content
6 of 9
added 1493 characters in body
Randomer11
  • 416
  • 11
  • 31

Order posts by meta value hiding posts instead of re-ordering

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.

I can't work out why its not working. Help would be appreciated.

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' );

EDIT ===================================

Following Jans comment below about a duplicate query, the only other customisations I have are the following. But removing them doesnt fix the problem so im a little stuck as to what the problem could be.

// Custom field Searching - Join posts and postmeta tables
 function custom_search_join( $join ) {
    global $wpdb;

    if ( is_search() ) {    
        $join .=' LEFT JOIN '.$wpdb->postmeta. ' cfmeta ON '. $wpdb->posts . '.ID = cfmeta.post_id ';
    }

    return $join;
}
add_filter('posts_join', 'custom_search_join' );

// Custom field Searching - Modify the search query with posts_where
function custom_search_where( $where ) {
    global $pagenow, $wpdb;

    if ( is_search() ) {
        $where = preg_replace(
            "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
            "(".$wpdb->posts.".post_title LIKE $1) OR (cfmeta.meta_value LIKE $1)", $where );
    }

    return $where;
}
add_filter( 'posts_where', 'custom_search_where' );

// Custom field Searching - Prevent duplicates
function custom_search_distinct( $where ) {
    global $wpdb;

    if ( is_search() ) {
        return "DISTINCT";
    }

    return $where;
    wp_reset_postdata();
}
add_filter( 'posts_distinct', 'custom_search_distinct' );
// Make sure custom post type can be searched.      
function custom_cpt_search( $query ) {
       if ( is_search() && $query->is_main_query() && $query->get( 's' ) ){
            $query->set('post_type', array('business'));
        }
        return $query;  
    };
    wp_reset_postdata();
    
add_filter('pre_get_posts', 'custom_cpt_search');
Randomer11
  • 416
  • 11
  • 31