Hey all, Hope you’re having a good day!
I’m working on integrating Cornerstone with the Image Placeholders plugin by the Wordpress Performance Team. It adds in dominant colour metadata on image upload, and adds it to images as a background colour. This of course doesn’t work out the box with Cornerstone.
I’ve got it working with image elements in Cornerstone using the 'cs_apply_image_atts'
filter, and here’s the code:
add_filter('cs_apply_image_atts', function ($atts) {
$src = $atts['src'];
$id = attachment_url_to_postid($src);
// if the src is not an attachment URL, return
if (!filter_var($src, FILTER_VALIDATE_URL) || !wp_attachment_is_image($id)) {
return $atts;
}
// get meta
$image_meta = wp_get_attachment_metadata($id);
// if the image meta is empty, return
if (! is_array($image_meta) || empty($image_meta['dominant_color'])) {
return $atts;
}
// add the dominant color as a style attribute
$style_attribute = '--dominant-color: #' . $image_meta['dominant_color'] . '; ';
$atts['style'] = isset($atts['style']) ? $atts['style'] . $style_attribute : $style_attribute;
$atts['data-dominant-color'] = $image_meta['dominant_color'];
if (isset($image_meta['has_transparency'])) {
$transparency = $image_meta['has_transparency'] ? 'true' : 'false';
$additional_classes = $image_meta['has_transparency'] ? ['has-transparency'] : ['not-transparent'];
$atts['data-has-transparency'] = $transparency;
$atts['class'] = isset($atts['class']) ? array_merge($atts['class'], $additional_classes) : $additional_classes;
}
return $atts;
}, 10, 1);
However, I require a change to core Cornerstone code in order to make it work with background image elements. It’s in cornerstone/includes/functions/helpers.php | Line 1540
. Currently it overrides the ['style']
attribute as below:
$bg_layer_img_atts['style'] = 'object-fit: ' . $the_img_object_fit . '; object-position: ' . $the_img_object_position . ';';
However, instead I recommend it appends these styles if a 'style'
attribute already exists. Using this option would put it in line with the way the image element itself works too. Like so:
$bg_inline_style = 'object-fit: ' . $the_img_object_fit . '; object-position: ' . $the_img_object_position . ';';
$bg_layer_img_atts['style'] = isset($bg_layer_img_atts['style']) ? $bg_layer_img_atts['style'] . $bg_inline_style : $bg_inline_style;
I’ve tested this code on a development site currently being built and it seems to be working as expected.
Would it be possible to have this change implemented? Otherwise, do any senior devs at Themeco have another recommendation on how this may be done?
Thanks for your time