Tribe__Events__Adjacent_Events::get_closest_event( string $mode = 'next' )
Get the prev/next post for a given event. Ordered by start date instead of ID.
Contents
Parameters
- $mode
-
(string) (Optional) Either 'next' or 'previous'.
Default value: 'next'
Return
(null|WP_Post) The closest Event post object, or null if no post was found.
Source
File: src/Tribe/Adjacent_Events.php
public function get_closest_event( $mode = 'next' ) {
global $wpdb;
$post_obj = get_post( $this->current_event_id );
if ( 'previous' === $mode ) {
$order = 'DESC';
$direction = '<';
} else {
$order = 'ASC';
$direction = '>';
$mode = 'next';
}
$args = [
'posts_per_page' => 1,
'post__not_in' => [ $this->current_event_id ],
'meta_query' => [
[
'key' => '_EventStartDate',
'value' => $post_obj->_EventStartDate,
'type' => 'DATETIME',
'compare' => $direction,
],
[
'key' => '_EventHideFromUpcoming',
'compare' => 'NOT EXISTS',
],
'relation' => 'AND',
],
];
$events_orm = tribe_events();
/**
* Allows the query arguments used when retrieving the next/previous event link
* to be modified.
*
* @since 4.6.12
*
* @param array $args
* @param WP_Post $post_obj
*/
$args = (array) apply_filters( "tribe_events_get_{$mode}_event_link", $args, $post_obj );
$events_orm->order_by( 'event_date', $order );
$events_orm->by_args( $args );
$query = $events_orm->get_query();
// Make sure we are not including same datetime events
add_filter( 'posts_where', [ $this, 'get_closest_event_where' ] );
// Fetch the posts
$query->get_posts();
// Remove this filter right after fetching the events
remove_filter( 'posts_where', [ $this, 'get_closest_event_where' ] );
$results = $query->posts;
$event = null;
// If we successfully located the next/prev event, we should have precisely one element in $results
if ( 1 === count( $results ) ) {
$event = current( $results );
}
/**
* Affords an opportunity to modify the event used to generate the event link (typically for
* the next or previous event in relation to $post).
*
* @since 4.6.12
*
* @param WP_Post $post_obj
* @param string $mode (typically "previous" or "next")
*/
return apply_filters( 'tribe_events_get_closest_event', $event, $post_obj, $mode );
}
Changelog
| Version | Description |
|---|---|
| 6.0.7 | Cache the query results. |
| 4.6.12 | Introduced. |