Creating the Difference

How to get correct event navigation

Posted on: 11-11-2018 Last modified: 03-07-2021
Categories: PHP, Snippets Tags:

If you are using the marvelous Events Manager plugin, you can choose to display your single event pages either as posts or pages. Depending on your theme, posts will usually display navigation links at the bottom of the post, while pages don’t. (Read more about the differences between these two.)

Why WordPress navigation links don’t work on Events.

The way WordPress creates the navigation links (previous post / next post) is solely based on its Post ID. Post IDs are automatically assigned to your new post/page/event/etc. by incrementing their value by one. (Read more about this in this article: WordPress Codex – Next and Previous Links.)

But, if you’re anything like me, you will probably not create all your events in a nice and structured and perfectly chronological order. :-) For me, it’s not uncommon that today’s event has ID 10, while tomorrow’s event got assigned Post ID 312 and the one a week from now has ID 178. See the problem here? Normally WordPress would arrange those to Post ID -> displaying: Today – Next Week – Tomorrow.

We want to have our visitors loop through our events based on start date, right?
Well, here’s how to do that.

Step 1: Create a shortcode for Event Navigation.

A shortcode is nothing more than a command between two brackets [ ], which calls a specific piece of code.

Add this to your functions.php:Click here to learn how to safely add your code to WordPress.

[php] function stonehenge_get_event_navigation() { // Using EM arguments makes it easier to filter the search results. // See $args = array( ‘status’ => ‘1’, // Only active events (not ‘Pending’). ‘scope’ => ‘future’, // Only upcoming events. ‘orderby’ => ‘event_start_date’, ‘blog’ => ‘all’, // Only applicable for MultiSite. ); $EM_Events = EM_Events::get($args, $count = false); $found_ids = array(); foreach( $EM_Events as $EM_Event ) { $found_ids[] = $EM_Event->post_id; } $current_post = get_the_ID(); $current_key = array_search($current_post, $found_ids); $next_key = $current_key + 1; $next_post = $found_ids[$next_key]; $prev_key = $current_key – 1; $prev_post = ($prev_key > 0) ? $found_ids[$prev_key] : ”; // Start output of the shortcode. $output = null; $output .= ‘‘; return $output; } add_shortcode(‘event-navigation’, ‘stonehenge_get_event_navigation’); [/php]

Step 2: Add the shortcode to your mark-up.

In your WordPress Admin Dashboard, go to Events → Settings → Formatting → Events → Single Event Page → Single event page format. At the very bottom of that textarea, type this:

Step 3: Add CSS styling (optional).

Your theme will probably have these classes defined in its css stylesheet already, but if not here is something to get you started: [css] .post-navigation { display: block; width: 100%; padding: 10px; } .nav-previous { float:left; } .nav-next { float:right; } [/css]
⇐ Previous
Next ⇒