You can use a jQuery plugin called Color Thief.
Files needed:
- jquery.js (is included in WordPress)
- quantize.js (download from color-thief github page)
- color-thief.js (download from color-thief github page)
WordPress setup:
Open functions.php
(located in your theme’s folder) and add the code below to load the files in WordPress. In this case I placed all files in the “js” folder.
//color thief demo
wp_register_script('quantize', $base . '/js/quantize.js');
wp_enqueue_script('quantize');
wp_register_script('colorThief', $base . '/js/color-thief.js');
wp_enqueue_script('colorThief');
wp_register_script('main', $base . '/js/main.js');
wp_enqueue_script('main');
As you can see I also created a main.js
file to store the code that will run the color-thief code.
main.js code:
jQuery(document).ready(function($) {
$("#target").load(function(){
// Dominant Color
var dominantColor = getDominantColor($(this));
//change background
$("body").css("background-color", "rgb("+dominantColor+")");
});
});
The code above will look for an image with id = target
.
The load()
function will ensure that the image has already loaded before the code is executed.
Next the value of the dominant color is stored in a variable (the value returned is 3 numbers, which form the RGB color)
We use that same variable to change the color of the background.
The HTML setup:
The TwentyEleven theme loads the image through a function in the file header.php
, but you can still edit the image tag and add an image ID to be able to find it easily with jQuery.
In this case my image ID is target
:
<img
src="https://wordpress.stackexchange.com/questions/94691/<?php header_image(); ?>"
width="<?php echo HEADER_IMAGE_WIDTH; ?>"
height="<?php echo HEADER_IMAGE_HEIGHT; ?>"
alt=""
id="target" />
And that should do it. Once the page loads, the jQuery script will look for an image with id = target
. Get the dominant color of that image, and then apply it to the background of the page automatically.
You can see a demo of this working here. (refresh the page a few times to until it loads a different image)