Support

Account

Home Forums ACF PRO Sort admin by last value in repeater field

Solved

Sort admin by last value in repeater field

  • Hi,

    I’m attempting to use pre_get_posts to sort a custom post type in the admin. The complication is that I want to use the first entry of a repeater field to do this.

    I have a repeater field attached to my post type called event_dates, inside that field I have a date field called event_dates_date along with some others like event_date_price and event_date_description. The event_dates_date field I am interested in returns the date as a Ymd string so I can sort them.

    The problem I have is that I can’t figure out how to target event_dates_date inside the event_dates repeater.

    add_filter('pre_get_posts', function ($query) {
        if ($query->is_admin) {
            if ($query->get('post_type') === 'event') {
                $query->set('orderby', 'meta_value');
                // Target the first instance of event_dates_date inside the event_dates repeater
                $query->set('meta_key', 'event_dates_date');
                $query->set('order', 'ASC');
            }
        }
        return $query;
    });

    Any pointers would be so very welcome!

  • If you are sure that you’ll only ever use the first row of the repeater then the meta key for your first date sub field will always be event_dates_0_event_dates_date

    As a side note, because of the way ACF names field you don’t need to name your sub field event_dates_date and you can just shorten that to date and this would result in the first row always having the meta key of event_dates_0_date

  • Thanks John, super useful!

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

You must be logged in to reply to this topic.