Skip to main content

Creating Conditional Placeholders for Events

Build an add-on

Part 8 of 11 in the Build an add-on series. Previous: Custom placeholder. Next: Multisite global tables.

Conditional placeholders wrap part of a format and show it only when a condition is true, as {has_bookings}...{/has_bookings} does. This part adds three for styles.

What you will build​

ConditionShows its content when
{has_styles}The event has at least one style
{no_styles}The event has no styles
{has_style_1}The event has the style with ID 1. Any style ID works in place of 1.
Before you start

Complete part 4, which provides $EM_Event->styles.

Steps​

  1. Add this line inside my_em_styles_init():

    add_filter( 'em_event_output_show_condition', 'my_em_styles_show_condition', 10, 4 );
  2. Add the function below to the end of the file.

Part 8: conditional placeholders
function my_em_styles_show_condition( $show, $condition, $full_match, $EM_Event ) {
$event_styles = (array) $EM_Event->styles;
if ( $condition === 'has_styles' ) {
return ! empty( $event_styles );
}
if ( $condition === 'no_styles' ) {
return empty( $event_styles );
}
if ( preg_match( '/^has_style_(\d+)$/', $condition, $matches ) ) {
return in_array( (int) $matches[1], $event_styles, true );
}
return $show;
}

How it works​

Before replacing ordinary placeholders, Events Manager looks for pairs of matching tags in braces. For each pair it decides whether the condition is true, then passes its decision through em_event_output_show_condition:

ArgumentContains
$showThe decision so far. For a condition Events Manager doesn't know, this is false.
$conditionThe name between the braces, for example has_style_1.
$full_matchThe whole block, from the opening tag to the closing tag.
$EM_EventThe event being formatted.

Return true to keep the content between the tags, or false to remove the block. For any condition that isn't yours, return $show unchanged. That last line matters: the filter runs for the built-in conditions too, and returning anything else would break them.

The regular expression accepts digits only, and the ID is compared as an integer against the integer IDs loaded in part 4.

Condition names can contain letters, digits, underscores, hyphens and commas. Blocks can be nested two deep with the default settings.

Test it​

  1. Add this shortcode to a page, with the ID of one of your styles:

    [events_list]
    <p>#_EVENTLINK {has_style_1}(formal dress){/has_style_1}{no_styles}(no style set){/no_styles}</p>
    [/events_list]
  2. Events with style 1 show "(formal dress)", events with no styles show "(no style set)", and events with only other styles show neither.

Next​

Part 9: Multisite global tables