WP SITES

2948 Tutorials & 189 Plugins

Random Images Using PHP Code

This PHP code enables you to display a random image which changes on every page load.

The solution only uses 3 lines of code in a custom function with WordPress or theme specific hooks like loop_start or genesis_after_header etc.

Note: If you’re wanting to rotate images in your themes header image, that functionality is already built into the WordPress customizer so you won’t need this solution which works anywhere you place the code in a template file or in any hook location.

In this example, the code uses 3 images from your child themes images folder and displays a different image every time the page loads.

The images should use the file names:

bg-1.jpg
bg-2.jpg
bg-3.jpg

You can change the filename and extension in the PHP code to match your images.

Demo Video

Here’s the code for registered members:

Related Tutorials

9 responses to “Random Images Using PHP Code”

  1. BobGillespie Avatar
    BobGillespie

    Hey Brad,

    I am using your random code in a function, works perfect but repeats same image on a grid of 6 posts on an archive page.

    Do you know a way to no-repeat the 6 random images, just show all 6 but in random order?

    Here is my function:
    add_action( ‘genesis_entry_content’, ‘bobg_image’ );
    function bobg_image() {
    if ( has_post_thumbnail( ) ) {
    $image = genesis_get_image( ‘format=url&size=portfolio-archive’ );
    } else {
    $image = sprintf( ‘%s/images/bckg-img-%s.jpg’, get_stylesheet_directory_uri(), rand( 1, 6 ) );
    }

    printf(‘%s‘ , get_permalink(), $image, the_title_attribute( ‘echo=0’ ), sk_return_post_title_archives() );
    }

    Thank you!

    1. Brad Dalton Avatar
      Brad Dalton

      Hi Bob

      What did you want the code to do exactly?

      I assume you want to display the featured image after the title on archives, if it exists, otherwise a random image, 1 of 6 added to your images folder? Where do you want the images linked to?

      I added some code to the post under the sub heading Use Featured Image Otherwise Random Image

      The images won’t be random unless the page has fully loaded before being reloaded so you might need to wait several seconds and in some cases, pages may take more than 10 seconds to fully load.

      1. BobGillespie Avatar
        BobGillespie

        Sorry, got called away from Dev with support issues and missed your reply.

        This code works better, more features but I still have repeated same image.

        The project (private, can’t share URL) is creating an exact copy of a non-Wordpress site.

        For each CPT archive I have a custom template and code to display latest 6 posts in a grid 3 across & 2 rows. Each post has just a background image with Title overlay and link to permalink.

        Default is all 6 posts use my 6 images from childtheme/images/image-1.jpg If the author chooses to add a Featured Image to post it will override default and display.

        The problem I have is the default images repeat, like post 2 and post 5 will display the same background image. In a grid of 6 visible posts this just looks bad when 2 are same

        Everything else works perfectly, the random is is working as expected but I can’t figure out how to check that an image isn’t displayed twice.

        Have been trying using array and some php like shuffle (from your reference link above) but just cannot get my head around the code to make it work.

        1. Brad Dalton Avatar
          Brad Dalton

          So we need to apply the random function to the latest 6 posts so each uses a unique image. Is there a deadline for this?

          I’ll have to set it up locally to try a few methods.

          The method os would use for the grid is this code https://wpsites.net/web-design/display-posts-in-columns-on-genesis-archive-pages/

          How about for paginated archive pages like the 2nd and 3rd pages of a CPT archive? Are you using the random function for this also?

          1. BobGillespie Avatar
            BobGillespie

            Just a Dev site so no big hurry.

            I have the columns working, everything is perfect except the duplicates.

            Here is my archive as a .txt file and a screenshot of the grid:
            http://nictechdesigns.com/share/

            See how my #1 and #3 then # 2 and #5 repeat same image.

            Pagination has been removed.

          2. Brad Dalton Avatar
            Brad Dalton

            Wrote and tested this code. Works perfectly for the latest 6 entries in the loop.

            Add 6 images named 1.png to 6.png in a folder named random and add the PHP code to your CPT archive template.

          3. BobGillespie Avatar
            BobGillespie

            Awesome, as usual you made something complicated a little easier to understand. Works perfectly, no repeat images.

            Thank you!

          4. Brad Dalton Avatar
            Brad Dalton

            I worked out a better solution. Just published the tutorial which includes both solutions

          5. Brad Dalton Avatar
            Brad Dalton

            Anytime Bob. If you could do me a small favor please and give me a endorsement based on your experience as a member of wpsites.net and the value it offers the community on the Genesiswp FB page when you have time i would be much appreciated. If not, no worries.

Was This Tutorial Helpful?