Support

Account

Home Forums General Issues Archive page with complex order by custom field

Unread

Archive page with complex order by custom field

  • Among all my custom post type I have one called event with a “date_of_event” custom field.

    In all archive pages I want to change the order my different custom post appear.

    Basically I am looking to achieve this order:

    – Future events ordered by “date_of_event” custom field (sooner events first)
    – All my other custom posts ordered randomly
    – Old events ordered by “date_of_event” custom field (closer events first)
    I have added a pre_get_posts filter in my function page which looks like this:

    function custom_archive_per_page( $query ) {
        if ( is_archive() ) {
    
            $query->set('meta_query', 
                array(
                    'relation' => 'OR',
                    array(
                        'key' => 'date_of_event',
                        'compare' => 'NOT EXISTS',
                    ),
                    array(
                        'key' => 'date_of_event',
                        'value' => date("Ymd"),
                        'compare' => '>',
                    ),
                    array(
                        'key' => 'date_of_event',
                        'value' => date("Ymd"),
                        'compare' => '<',
                    ),
                )
            );
            $query->set('orderby', 
                array(
                    'meta_value_num' => 'DESC',
                    'title' => 'ASC',
                )
            );
        }
    }
    add_filter( 'pre_get_posts', 'custom_archive_per_page' );

    This gives me this order.

    – Future events ordered by “date_of_event” custom field (sooner events first)
    – Old events ordered by “date_of_event” custom field (closer events first)
    – All my other custom posts ordered by title

    Does anyone knows how to move all events with older dates after all my other custom post type in the query?

    Thanks for you help.

Viewing 1 post (of 1 total)

The topic ‘Archive page with complex order by custom field’ is closed to new replies.