The background image is applied to the <body>
element, so using jQuery, all you really need to do is add a .click()
handler to the $('dt.gallery-icon img')
element, grabbing its src attribute and applying it to the body's background-image
.
EDIT: I thought this would be an interesting exercise, so here is a plugin that does what you want (as far as I understood it). Go into wp-content/plugins
and create a new file. Call it whatever you like. Paste this into your new file. Then go into the WordPress Admin back end and activate the new plugin.
<?php
/*
Plugin Name: SE-32426 BackgroundGallery
Plugin URI: http://wordpress.stackexchange.com/questions/32426/how-to-change-background-image-from-wordpress-gallery
Description: Click on any image of a default WP gallery, and that image is displayed in the background image.
Author: @TomAuger
Author URI: http://www.tomauger.com
License: GPL2
*/
class SE32426_BackgroundGallery {
// Make sure jQuery is loaded. If it already is, then this will do nothing.
static function enqueue_jquery(){
wp_enqueue_script( 'jquery' );
}
// Add our own javaScript to the top of the WordPress gallery section.
// Another way to do this would be to create a separate .js file and enqueue it like we did above.
static function add_gallery_script( $output ){
$output .= <<<END_JAVASCRIPT
<script type="text/javascript">
jQuery(document).ready(function($) {
$('dl.gallery-item img').click(function(event){
// Prevent the click from actually going through and linking to the attachment post page
event.preventDefault();
// The image we clicked on is probably a thumbnail. We want the full image.
thumbImg = $(this).attr('src');
fullImg = thumbImg.replace(/-[^-.]+(\..+)$/, "$1");
// Set the body's background image to the image we just clicked on.
$('body').css('background-image', 'url(' + fullImg + ')');
});
});
</script>
END_JAVASCRIPT;
return $output;
}
}
add_action( 'init', array( 'SE32426_BackgroundGallery', 'enqueue_jquery' ) );
add_filter( 'gallery_style', array( 'SE32426_BackgroundGallery', 'add_gallery_script' ) );