Add dominant color in the WordPress images style to use as background-color for WooCommerce products

This should work for all images you attach to your WordPress website through the media gallery

Chelaru Adrian
3 min readJul 26, 2023

If you have a smaller scale image, but you don’t like the space that is let blank at the sides of it, you can consider adding a colored background to it so the free space of the for example object-fit: contain;, can be masked with an in-place fitted to image color.

Example product with fixed height, contain fit and big margins, at right with the dominant color as background

We can do this using a plug-in and a bit of code for functions.php (Code Snippet).

First, download and install the Dominant Color module.

Now, you can insert the code below into your functions.php (Code Snippet):

/*
*
* This function will filter the standard image HTML output to add the dominant color
* as hex data attribute and CSS variable
*
*/
add_filter('wp_get_attachment_image', 'add_dominant_color_palette_hex_attr_on_image', 10, 5);
function add_dominant_color_palette_hex_attr_on_image($html, $attachment_id, $size, $icon, $attr) {
//Exit if is admin panel or the plugin is disabled
if ( is_admin() || !function_exists('get_color_data')) return $html;

// Get the attachment metadata
$attachment_metadata =…

--

--

Chelaru Adrian
Chelaru Adrian

Written by Chelaru Adrian

💻 Hey, I'm here to share my passion for tech! 🚩 Follow me on Medium for exciting new ideas and innovative solutions.

No responses yet