Bricks Builder - Add a custom control to every element

Published on by in Tutorials.

Following this tutorial by Maxime, we know how to add a custom control to an element in Bricks by using the bricks/elements/{element_name}/controls filter.

Another question comes up is how can we add a custom control to every element?

The challenge of adding a custom control to every element is that we don’t know the {element_name} of every element since elements can be added dynamically?

Skim through Bricks’ codebase, you will see that Bricks initializes elements on the init hook with the default priority (10):

Bricks loading elements hook

After being initialized, elements are stored in the property $elements in the same class (Bricks\Elements). And you notice some thing, right? Yeah, it’s a public static property so we can access it from outside the Bricks\Elements class instance.

And, given that Bricks initializes all elements on the init hook with the default priority, we will hook into the init hook with a higher priority, loop through all the initialized elements, then apply the bricks/elements/{element_name}/controls filter.

For example, I use below code to add an Entrance Animation control to every element:

<?php

/**
 * @return void
 */
function wpc_on_wp_init()
{
    if (!class_exists('Bricks\Elements')) {
        return;
    }

    $elements = Bricks\Elements::$elements;

    foreach ($elements as $element) {
        $hook = 'bricks/elements/' . $element['name'] . '/controls';
        add_filter($hook, 'wpc_filter_bricks_controls', PHP_INT_MAX);
    }
}
add_action('init', 'wpc_on_wp_init', PHP_INT_MAX);

/**
 * @param array $controls
 * @return array
 */
function wpc_filter_bricks_controls($controls)
{
    if (!class_exists('Bricks\Setup')) {
        return $controls;
    }

    $controls['_animationSeparator'] = [
        'tab'   => 'style',
        'group' => '_layout',
        'label' => esc_html__('Animation', 'text-domain'),
        'type'  => 'separator',
    ];

    $controls['_animation'] = [
        'tab'         => 'style',
        'group'       => '_layout',
        'label'       => esc_html__('Entrance Animation', 'text-domain'),
        'type'        => 'select',
        'searchable'  => true,
        'options'     => Bricks\Setup::$control_options['animationTypes'],
        'inline'      => true,
        'placeholder' => esc_html__('None', 'text-domain'),
    ];

    return $controls;
}

There I use the PHP_INT_MAX to ensure that all initialized elements are available when applying the filter.

That’s it. Try it out. If you have any questions or a better solution, let us know in the comment section.