Skip to main content

Adding Information to Events on Load

Build an add-on

Part 4 of 11 in the Build an add-on series. Previous: Save event data. Next: Search attributes.

The styles are in the database, but nothing reads them yet. This part loads them into each event object, so that $EM_Event->styles is available wherever an event is used: the editor from part 2, and the placeholders, conditions and pages in later parts.

What you will build​

A callback on the em_event action that sets $EM_Event->styles to an array of style IDs.

Before you start

Complete part 3 and save at least one event with a style.

Steps​

  1. Add this line inside my_em_styles_init():

    add_action( 'em_event', 'my_em_styles_event_load' );
  2. Add the function below to the end of the file.

Part 4: loading
function my_em_styles_event_load( $EM_Event ): void {
$EM_Event->styles = my_em_styles_get_event_style_ids( (int) $EM_Event->event_id );
}

How it works​

em_event is the last thing the EM_Event constructor does. It passes the finished object, so anything you set on it is there for the rest of the request. The action also passes the ID and the search type the object was loaded with as its second and third arguments, which this callback doesn't need.

my_em_styles_get_event_style_ids() is the helper from the overview. It returns an empty array for an event with no ID, so a new, unsaved event gets an empty list instead of an error.

Three things to keep in mind when you load data this way:

  • The callback runs for every event object, including each item in a list of fifty. One small indexed query per event is acceptable here. For anything heavier, load on demand in a function instead, or fetch for the whole list at once on the em_events_get filter.
  • Events Manager caches event objects for the length of a request, so the same event loaded twice runs the callback once. With a persistent object cache, a cached event already has its styles attached. Part 3 updates the property when it saves, which keeps the cached copy correct.
  • Recurrences need no special handling, because part 3 stored the styles against each recurrence's own event_id.

Test it​

  1. Reopen the event you saved in part 3. Its style is now ticked in the Styles box.

  2. Untick it and update. The box stays unticked after the page reloads, and the row is gone from the em_meta table.

  3. To see the property directly, run:

    wp eval 'var_dump( em_get_event( 17 )->styles );'

    Replace 17 with the event_id of an event that has a style. The output is an array of integers.

Next​

Part 5: Search attributes