WordPress.org

Ready to get started?Download WordPress

Forums

Posts are unexpectedly filtered by meta_key (2 posts)

  1. gordo54
    Member
    Posted 1 year ago #

    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?

  2. vtxyzzy
    Member
    Posted 1 year ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic