Home Forums Front-end Issues Send posts that have a specific ACF meta field empty to the bottom


Send posts that have a specific ACF meta field empty to the bottom

  • I realise this is leaning towards a straight up WP question rather than an ACF question but my query uses two ACF and the query is sorted by both, and the issue is connected to one of them! Hopefully you can help 🙂

    I have the following code which loops through Woocommerce products and orders them by two ACF – firstly by start date (which is a date picker field) and then secondly by duration (text input field). This works fine – except for tours that don’t have start dates assigned. These are output at the top of the list, and I’d like them to be at the bottom of the list of results, so that the user sees the items with start dates assigned first. Any ideas how to amend this query to achieve that?

    $tours = new WP_Query(array(
    ‘post_type’ => ‘tour’,
    ‘posts_per_page’ => -1,
    ‘meta_query’ => array(
    ‘relation’ => ‘AND’,
    ‘start_date’ => array(
    ‘key’ => ‘start_date’,
    ‘duration’ => array(
    ‘key’ => ‘duration’,
    ‘type’ => ‘NUMERIC’,
    ‘orderby’ => array(
    ‘start_date’ => ‘ASC’,
    ‘duration’ => ‘ASC’,

    Just to recap – the output all the tours without a start date set at the top of the list of results, followed by all the tours with a start date (in the correct chronological order).

    What I want is the chronological tours first, tours with blank start dates last.

    —- Versions —-
    ACF v5.8.7
    WP v 5.3.2

  • Thanks John. I don’t actually understand the solution in that thread. I think I may have to do what I originally thought of, something I didn’t want to do – move them with javascript. It works, it’s just hacky. Was hoping there was a nice query amend I could make that I’d missed in the search…

  • What that post is saying is this.

    Do your query as you are doing it and add a posts_results filter. In this filter you short the posts into two arrays: those that have a start date and those don’t have a start date. Then you merge the two arrays and return the resorted posts.

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Send posts that have a specific ACF meta field empty to the bottom’ is closed to new replies.