WordPress.org

Ready to get started?Download WordPress

Forums

Change iframe src on refresh? (2 posts)

  1. jimmytuesday
    Member
    Posted 1 year ago #

    I have an embedded Vimeo video on my homepage (In the index.php template file) and I am using their embed code which makes use of iframes. (I target the iframe in my video menu underneath, so that works well for what I'm doing.)

    I'd like that video area, the iframe, to display one of three different videos (randomly chosen) when you load the page. When you refresh the page a different video, presumably, would load.

    I think what I need is some Javascript that, for this one little section of my site, will choose between 3 different code snippets (3 different vimeo embeds) every time the page loads, but I'm a bit of newbie at Javascript and at a loss of how to do this.

    Does anyone have any suggestions? Am I barking up the wrong tree?

    Thank you for any help!

  2. catacaustic
    Member
    Posted 1 year ago #

    Seeing as how you're doing this in a template, I wouldn't use JavaScript. You're better off using PHP to be able to do this.

    $urls = array (
      "http://site.com/video1.mp4",
      "http://site.com/video2.mp4",
      "http://site.com/video3.mp4"
    );
    
    $rand = mt_rand (0, count ($urls) - 1);
    
    echo "<iframe src='".$urls [$rand]."'></iframe>";

    What you're doing there is setting u the video URL's, then generating a random number between 0 and 2 (in PHP all array indexs start at 0, not 1 so for an array with three items you choose between 0 and 2, not 1 and 3). From there you output the value at that index. That will give you a random video URL each time, and all you need to do to add in another video URL is to add a new line in the $url array.

Topic Closed

This topic has been closed to new replies.

About this Topic