Tuesday, June 2, 2015

Change background image randomly from a directory using Ajax in WordPress

A couple weeks ago, I'm working on a project that required me to develop a WordPress theme. One of the things that interested me was to create a block (html, in the front page) that change its background image randomly every time I reload the page. Here is how I did that:

The main idea here is using Ajax to dynamically change background of a div tag to a random image loaded from a folder inside the theme's root every time I reload the home page.

1. functions.php

add_action('init', 'enqueue_scripts_styles_init');
function enqueue_scripts_styles_init() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/myscript.js', array('jquery'));
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
add_action('wp_ajax_get_rand_img', 'get_rand_img');
add_action('wp_ajax_nopriv_get_rand_img', 'get_rand_img');
function get_rand_img() {
  $path = get_template_directory() . '/img/*.*';
    $files = glob($path);
    $file = array_rand($files);
    $img = str_replace(get_template_directory(), get_template_directory_uri(), $files[$file]);
    echo $img;

2. page-home.php (my homepage template)
          <div id="my-img-block">

3. /js/myscript.js (the javascript)

jQuery(document).ready(function() {

function RandomImagesBlock() {
method: "POST",
url: ajax_object.ajaxurl,
data: {
'action': 'get_rand_img',
}).done(function( filename ) {
jQuery('#my-img-block').css('background', 'url('+filename+')');
jQuery('#my-img-block').css('background-size', 'cover');

Then I only need to drop any image into the /img/ folder inside the theme's root, they will be loaded randomly (and changing) every time a user load the home page.

Pretty cool huh? \m/

[0] http://www.dangtrinh.com/2015/05/get-image-randomly-from-directory-and.html
[1] http://web-profile.com.ua/wordpress/dev/ajax-in-wordpress/