WordPress.org

Ready to get started?Download WordPress

Forums

WP_Query sorting by meta_key, excluding some posts (2 posts)

  1. davidsword
    Member
    Posted 3 years ago #

    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

  2. vtxyzzy
    Member
    Posted 3 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic