How to display random image when page loads in WordPress

Several years ago, I used a WordPress plugin named "Random Content" to display random content. I think you might be able to use this plugin to display random image when loading a page in WordPress.

However, this plugin was updated one year ago. Therefore, it would be desirable not to use it.

There is also a plugin "WordPress Random Image", however it's also has not been update for about 1 year.

It's possible to display image randomly using simple javascript. Google search will display many articles containing javascript code to display random image.

For example, you can use the following code found at https://stackoverflow.com/questions/2777479/display-random-image-when-page-loads-without-utilizing-onload-in-the-body-tag:

<script type="text/javascript">
var imageURLs = [
"http://www.example.com/images/image1.png"
, "http://www.example.com/images/image2.png"
, "http://www.example.com/images/image3.png"
];
function getImageTag() {
var img = '<img src=\"';
var randomIndex = Math.floor(Math.random() * imageURLs.length);
img += imageURLs[randomIndex];
img += '\" alt=\"Some alt text\"/>';
return img;
}
</script>

You can insert this script to your theme's header.php file. Or, if you want to apply it a specific page, you can enque this js script.

For example, please create a js file to containing the above script except <script type="text/javascript"> and </script>. And then, upload this file onto your child theme's sub-directory (e.g. /wp-content/themes/your-child-theme/js/random_image.js.)

Now add the following code to your child theme's function file:

function random_scripts_method() {
wp_register_script('random-scripts', get_stylesheet_directory_uri() . 'js/random_image.js', array('jquery'), '1.0', true);
wp_enqueue_script('random-scripts');

}
add_action( 'wp_enqueue_scripts', 'random_scripts_method' );

If you want to apply this script to specific pages, the following code will work:

function random_scripts_method() {
wp_register_script('random-scripts', get_stylesheet_directory_uri() . 'js/random_image.js', array('jquery'), '1.0', true);
if ( is_page( 'careers' ) ){ // this script will be enqueued only on the page "careers"
wp_enqueue_script('random-scripts');
}
}
add_action( 'wp_enqueue_scripts', 'random_scripts_method' );

Please refer to this document for more about the is_page() function.

Next, please place the following code where you want to display random image:

<script type="text/javascript">
document.write(getImageTag());
</script>

In Avada, you can use the Code Block element to insert the code.

When using Visual Composer (now "WPBakery Page Builder"), you can use the Raw HTML element. For example, the following shows the Raw HTML element in The 7.

If the above script does not work, you can perform some search to find a working js script.


Leave a Comment