Adding Related Events Using Advanced Custom Fields
Requires Event Espresso 4.8.x and above.
In this tutorial, we’ll create a “Related Events” section ( example) that will be displayed in the event details page. We’ll be using example code from the ACF plugin documentation for Relationships and action hooks available to us within Event Espresso 4.
Add a New ACF Field Group for Related Events
- Create a new ACF Field Group (WP Admin > Custom Fields > Add New) [screenshot]
- Using the screen shot as a guide, add the following field to the group:
Events (events | Relationship | espresso_events)- Field Name: events
- Field Type: Relationship
- Post Type: espresso_events
- Set the “Show this field group if ” setting to “Post Type > is equal to > espresso_events”.
- [optional] Change the order, position, and style of the meta box in the EE4 event editor.
Add a Custom Hook
Next we need to add the code that will output the related events. There are actually two options, which I will outline below:
- Option 1: Child Theme
Add the following code to the functions.php file in a child theme. For more information about child themes, checkout the WordPress Child Theme Documentation. - Option 2: Site Specific Plugin[Recommended] Create a site specific plugin using the code below. For more information about site specific plugins, check out our documentation on the subject.
function ee_related_events() { $posts = get_field('events'); if( $posts && is_singular( array( 'espresso_events') ) ): ?> <div class="related-events"> <h3 class="event-venues-h3 ee-event-h3">Related Events</h3> <ul> <?php foreach( $posts as $p ): // variable must NOT be called $post (IMPORTANT) ?> <li> <a href="<?php echo get_permalink( $p->ID ); ?>"><?php echo get_the_title( $p->ID ); ?></a> </li> <?php endforeach; ?> </ul> </div> <?php endif; ?> <?php } add_action( 'AHEE_event_details_after_the_content', 'ee_related_events' );
The snippet above uses an EE4 action hook called “AHEE_event_details_after_the_content” to display the contents of the “ee_related_events()” function, which contains the HTML for the related events. The data for the ACF field is pulled from the WP global $post variable. So you can add post data (description, date, etc.) to the output if you like.
Create a New Event & Add Related Events
- Create a new Event Espresso event (WP Admin > Event Espresso > Events > Add New Event)
- In the new meta box generated by ACF using the steps outlined above, select the related events. [screenshot]
- Publish the event.
View the Event on the Front-end
You should end up with something like this in the event details:
Finishing Up
That basically covers adding a related events to a single event. You can easily add other post types, like venues, attendees, posts, pages, etc.
Related Articles
Add a Course Curriculum Section to the “Thank You” Page Using Advanced Custom Fields
Add a Sponsors Section to Events Using Advanced Custom Fields