open
30.12.2022.

WordPress random image from directory

How to use a randomly selected image from a folder? If you use the code snippet below, the code will select an image from a random folder in the uploads folder.

The advantage is that if you use it several times within a page, it will not repeat more than likely, so it will not display the same lifeless image as the picsum photos.


<?php bloginfo('url'); ?>/<?php $dir = 'wp-content/uploads/random';$files = scandir($dir);$index = rand(2, count($files)-1);$selectedImage = $files[$index];echo ''.$dir.'/'.$selectedImage.'';?>
Copy to Clipboard

live demo here


Related posts

Got a question? Is something not working? Write and I'll answer!

Leave a Reply

Your email address will not be published. Required fields are marked *