0

I'm trying to sort custom post type made with ACF plugin by most current date. Ideally future most current post should be first. Currently, I'm sorting by date, which gives me the earliest post as the first post.

Here is my code.

$loop = new WP_Query( array( 
    'post_type'             => 'events', 
    'posts_per_page'        => -1,
    'meta_key'              => get_sub_field( 'date_start' ),
    'orderby'               => 'meta_value_num',
    'order'                 => 'ASC'
) ); 

Here is the screenshot of my website to make things clear. enter image description here

I have tried this post to no avail https://stackoverflow.com/questions/28951370/sort-wp-query-by-acf-datepicker

It seams that my meta_query is not properly setup. This is the meta_query that I tried.

'meta_query' => array(
    array(
        'key' => get_sub_field( 'date_start' ),
        'compare' => '>=',
        'value' => current_time('Ymd'),
        )
),

note: for some reason I have to do get_sub_field('date_start') plain 'date_start' doesn't return any results.

5
  • Is date_start a sub-field of a repeater or group field? Also, get_sub_field() and get_field() return the value for the current post. It doesn't make any sense to use it as the key. Commented Jan 23, 2020 at 7:01
  • date_start belongs to a group. This totally make sense, but for some odd reason I can't get any result without using get_sub_field(). Commented Jan 23, 2020 at 7:30
  • 1
    If you're getting a result with get_sub_field(), it's almost certainly incorrect, and by coincidence. If date_start is the sub field of a group, then the meta key will not be date_start, it will be prefixed with the group's key. Commented Jan 23, 2020 at 7:36
  • Thanks, that actually make perfect sense. Commented Jan 23, 2020 at 8:30
  • @Jacob, thanks for your input, it did the trick. Learn something everyday Commented Jan 23, 2020 at 8:39

1 Answer 1

1

So thanks to Jacob Peattie and his helpful comments I was able to resolve this issue.

meta_key was part of the group, but it wasnt prefixed by a group key. So, something like this totally works for me: group_field_sub_field. So changing that in both arrays did the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.