Skip to content

Adding A Condition

Frank Corso edited this page Oct 7, 2020 · 3 revisions

Using Popup Maker's condition system, you can specify exactly where a popup should be loaded. These conditions can be either PHP or JS based. Let's add two conditions to see how this works.

The conditions are stored as an array within Popup Maker. We can add new conditions by adding new arrays to the existing conditions.

Some conditions will also need some input from the admin. For example, our built-in Post: Selected requires the admin to select which post to show the popup on. You can pass any of our Popup Maker Fields into the fields key for the condition (docs on fields coming soon).

PHP-based Condition

In this example, we will be adding a condition that, when added to a popup, will check if the post title starts with "Example:". Admins could then use this condition to show popups only on a post with a title starting with "Example:" or show popups on all pages except a post with a title starting with "Example:".

First, we need to register the condition using the pum_registered_conditions filter.

/**
 * Adds our example condition
 *
 * @param array $conditions The existing registered conditions.
 * @return array The updated conditions array
 */
function pum_example_title_condition( $conditions = array() ) {
    return array_merge( $conditions, array(
        'is_example' => array( // The ID for the condition
            'group'    => __( 'General', 'popup-maker' ), // The section within the conditions drop-down to add this condition to.
            'name'     => __( 'Example Post', 'popup-maker' ), // The name that appears to admins when selecting the condition.
            'priority' => 10, // The priority determines the order the conditions are listed in within the group. Lower appears higher in the list.
            'callback' => 'pum_example_title_condition_callback', // The function to call to determine the state of the condition.
            'fields'   => array(), // If you need to show a text box/drop-down to get input from the admin, you can pass fields here.
        ),
    ));
}

add_filter( 'pum_registered_conditions', 'pum_example_title_condition' );

Now that we have our condition registered, we need to create a callback function that will be used when a popup uses this condition. Callback functions should return true if the condition is valid or false if the criteria for the condition fails.

/**
 * Determines if the post is an example post
 *
 * @param array $condition The condition settings, including input into any `fields`, if registered with the condition.
 * @param array $popup The current popup that is being checked.
 * @return bool
 */
function pum_example_title_condition_callback( $condition, $popup ) {
    if ( strpos( get_the_title(), 'Example:' ) !== false ) {
        return true;
    }
    return false;
}

JS-based Condition

Coming soon...