Using focal points for background images

We were looking for a way to respect the media focal point set in WordPress when using background images in Bricks since Bricks doesn’t yet have built in support for focal points. For our project we only needed background image support, so here’s how we handled this.,

We’re using the free Media Focus Point plugin, which lets you set a focal point visually in the Media Library. To make use of that in Bricks, we wrote a small helper function that outputs just the CSS needed to position the background correctly, and it works with the {echo:} tag inside Bricks templates. You will need to have code execution set up.

Here’s the PHP:

function focus_bg( $img_id = null ) {
	if ( empty( $img_id ) ) {
		$img_id = get_post_thumbnail_id();
	}
	if ( ! $img_id ) {
		return ''; // nothing to add
	}
	return MFP_Background( $img_id, false );
}

//whitelist the function
add_filter( 'bricks/code/echo_function_names', function() {
	return [ 'focus_bg' ];
} );

To use it, we just drop this into the Style attribute of the container that already has a dynamic background image:

  • In the “Attributes” panel in the Bricks sidebar
  • Add a new attribute:
  • Name: style
  • Value: {echo:focus_bg}

It outputs something like:

<div style="background-position: 50% 25%; background-size: cover;">

That way, the cropping respects the focus point set in the Media Library. Hope this is helpful for others!

1 Like

Didn’t know about this Plugin… I think it’s a neat idea to set the focus-point globally per image!

I played around with it and if you are mainly using one Element e.g. the Section with Background Images you can add this Code-Snippet to programmatically add the Focus-Point:

add_filter('bricks/element/render_attributes', function ($attributes, $key, $element) {
    if (bricks_is_builder_main()) return $attributes;

    if ($element->name !== 'section')  return $attributes;

    $img_id = $element->element['settings']['_background']['image']['id'] ?? false;

    if (!$img_id) return $attributes;

    $image_pos = get_post_meta($img_id, 'bg_pos_desktop', true);

    if (empty($image_pos)) return $attributes;

    $image_pos_style = "background-position: {$image_pos};";

    if ($key !== '_root') return $attributes;

    $attributes[$key]['style'] = $image_pos_style;

    return $attributes;
}, 10, 3);

The Focus-Point Value gets saved as bg_pos_desktop Post-Meta per Attachment.

And by the way, I would suggest you make your code a bit more robust, by checking if the MFP_Background Function exists first. Otherwise you might crash your site, if you ever disable the Plugin.

    if (!function_exists('MFP_Background')) return '';    
    return MFP_Background($img_id, false);

Cheers Suat

1 Like

Hey Thank you SuatB! Greatly appreciated across the board, and you caught my sloppiness with checking for the function. Cheers!