• I am executing a WordPress Query that I expect to order the results by my meta_key. But in addition to the ordering, WordPress is filtering the results as well, and posts that do not contain a value for the specified key are not showing.

    Here is my args array:
    Array ( [posts_per_page] => 6 [cat] => 5 [paged] => 1 [orderby] => meta_value_num [order] => DESC [meta_key] => rating )

    Any idea what I am doing wrong?

Viewing 1 replies (of 1 total)
  • You cannot use a meta_key argument in a query and still retrieve posts without the specified key. You will need to use filters to alter the query.

    You can find the filters used in the code below in this article.

    Copy the filters into your functions.php. Be careful though. If you make a mistake in functions.php, it will disable your site and you will have to use ftp to edit the file to correct the error.

    You will need to eliminate the ‘orderby’, ‘order’, and ‘meta_key’ parameters from $args and handle the meta value in the filters.

    This is UNTESTED.

    Create a sort_key field with the fields filter (change the 0 to 9999999′ if you want missing code’s to sort before the projects, assuming order is DESC):

    $mam_global_fields = ', IFNULL(pm.meta_value,0) AS sort_key';

    Set the join filter to join the postmeta table:

    $mam_global_join = " LEFT JOIN $wpdb->postmeta pm ON (pm.post_id = $wpdb->posts.ID AND pm.meta_key = 'rating')";

    Set the order to the sort_key:

    $mam_global_orderby = 'sort_key DESC';

    After the query, set the 3 $mam_global_… fields to an empty string to turn the filters off so they will not affect future queries.

Viewing 1 replies (of 1 total)
  • The topic ‘Posts are unexpectedly filtered by meta_key’ is closed to new replies.