Support » Fixing WordPress » WP_Query sorting by meta_key, excluding some posts

  • When I sort my WP_Query with meta_key, if a post doesn’t have that meta key set it doesn’t show up in the results..

    my_meta_value = 1 (or) 0 (or) !isset()

    ie:

    $q = new WP_Query(array('orderby'=>'meta_value','meta_key'=>'my_meta_value'))

    returns only 3 results (three withmy_meta_value set),

    $q = new WP_Query(array('orderby'=>'meta_value'))

    returns 20 results (what I expect). but is not ordered properly

Viewing 1 replies (of 1 total)
  • This can be done using filters. See this article for the filter functions needed:

    http://wordpress.mcdspot.com/2010/05/30/filters-to-modify-a-query/

    Use code like this to enable the filters. Note that this is untested and may have typos. I have tried to make it close to what you need, but it is only an example.

    global $mam_global_fields, $mam_global_join, $mam_global_orderby;
    $mam_global_fields = ' IFNULL(metax.meta_value, " ") AS sortkey';
    $mam_global_join = " LEFT JOIN $wpdb->postmeta metax ON ($wpdb->posts.ID = metax.post_id AND metax.meta_key = 'my_meta_key')";
    $mam_global_orderby = "sortkey ASC, $wpdb->posts.post_date ASC";
    
    $q = new WP_Query(array('posts_per_page' => -1));
    
    // Turn off the filters
    $mam_global_fields = $mam_global_join = $mam_global_orderby = '';
Viewing 1 replies (of 1 total)
  • The topic ‘WP_Query sorting by meta_key, excluding some posts’ is closed to new replies.