• Hello, I’m trying to order a WP_Query. I currently have it working – ordering a list of personnel by custom fields (group, rank) and post date. This is working a treat with one exception. The post date is actually date of hire which is fine, but I have another custom field for promotion date and need to order by that field first, then by post date. I’m at a complete loss here. Here is my current code:

    // Query Arguments to order posts by Group, Rank, and Seniority
    $args = array(
    'post_type' => 'personnel ',
    'posts_per_page' => -1,
    'meta_query' => array(
    'relation' => 'AND',
    'group_clause' => array (
    'key' => 'group',
    'value' => 'Resigned/Retired/LODD',
    'compare' => '!=',
    ),
    'rank_clause' => array(
    'key' => 'rank',
    'compare' => 'EXISTS',
    ),
    ),
    'orderby' => array(
    'group_clause' => 'ASC',
    'rank_clause' => 'DESC',
    'date' => 'ASC',
    ),
    );

    // Query the database
    $loop = new WP_Query( $args );

    I’ve tried adding promotion_clause => array but I need to include all the posts – even those without a promotion date. Is there a way to order by promotion date first if it exists, then by post date?

    Thanks in advance

    The page I need help with: [log in to see the link]

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    If you specify orderby promotion date before post date and some posts have no such promotion field, SQL will bunch all such posts together and order them within that group by post date. AFAIK it’s not possible to conditionally use post date as promotion date when promotion date does not exist. For that kind of logic I think you’d need to use usort() to order the found posts after the query has completed but before output begins. The problem with using usort() is it makes pagination difficult. You need all posts found for it to work, not just a page’s worth of posts.

    Thread Starter cwcrogan

    (@cwcrogan)

    I see. I didn’t know if SQL could select all the records and order (sort) by a field, whether null or not, and then sort by post date. I was also curious if an OR would work using promotion date/post date – but I’m not very familiar with SQL.

    To solve my issue, I just placed start (post) date in the promotion field for all records. There’s a limited number of records (posts) so it wasn’t difficult to do, I just would rather have done it logically.

    Thank you.

    • This reply was modified 5 months, 3 weeks ago by cwcrogan.
Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.