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() ) {
    // 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' );

1 Answer 1


Literally seconds after updating this post I found the solution....again, Must have looked at this previously and not entered the details correctly as I tried this one before. :)

    add_action('pre_get_posts', 'add_special_sort', 11, 1);
function add_special_sort($query){
  // Bail if not the main "hidden" query, as opposed to a 'new WP_Query()' call

  $query->set('meta_query', array(
    'relation' => 'OR',
      'key' => 'featured_listing',
      'compare' => 'NOT EXISTS',
      'key' => 'featured_listing',
      'compare' => 'EXISTS',
  //$query->set('meta_key', NULL);
  $query->set('orderby', array('meta_value_num' => 'DESC', 'date' => 'DESC'));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.