Support

Account

Home Forums ACF PRO ACF Datetime Query – Find Prev and Next Events

Solving

ACF Datetime Query – Find Prev and Next Events

  • Hi, I am using the datetime field for an events management system and I have come across a problem I cannot solve.

    When looking at an event I need to be able to find the previous event and the next event to display at the bottom of the page. This would be relatively simple BUT some events have the same start time. For example:

    Event 1: 2020-09-09 08:00:00
    Event 2: 2020-10-09 08:00:00
    Event 3: 2020-10-09 08:00:00
    Event 4: 2020-11-09 08:00:00

    If the start times were unique I could simply run a couple of custom queries like so to get the event before and after this one:

    array (
    	'post_type' => 'my_cpt_name',
    	'posts_per_page' => '1',
    	'meta_query' => array (
    		'datetime_clause' => array (
    			'key' => 'event_time',
    			'compare' => '>',
    			'value' => $datetime
    		)
    	)
    	'orderby' => array (
    		'datetime_clause' => 'ASC'
    	)
    )

    But because events can start at the same time this will ignore any of those events.

    So is there a simple way to get prev & next post IDs that I’m unaware of?

    Or is there a way I can use the post ID in this query to add to the ordering?

    I’d be grateful for any advice. Thanks!

    John..

  • That really depends on how you are ordering the posts in the first place, for example on the event archive page.

    Do you also have an end time field?
    Are you just ordering the posts by the start time?

    if you are just using the single field then WP is ordering them first by this field and then in the order that the posts were created. This would mean that the next post of the same time would be the post with a larger ID and the previous post would be a post with a smaller ID.

    But I’d need more information about what you consider the previous and next post based on the order you’d expect them to appear in a list.

  • Hi, thanks for the reply. I should have explained that this is below the content on a single-cpt.php page.

    What I think I will do is run the above query and create an array of ordered post IDs. Then I’ll find the current post’s ID and choose the IDs directly before and after my one.

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

You must be logged in to reply to this topic.