This is a quick and relatively easy way to add random hero images for YOOtheme Pro. You can use this for vanilla WordPress as well…just ignore the bits about sections.
Assumptions
- You have a YOOtheme Pro theme and know your way around.
- You have a Yootheme child theme setup.
- You have access and can edit your functions.php file.
Steps
- Add your hero images to the website. I typically size mine to 2400×1600.
- In the Builder’s section where you’d like your photo background to appear, give it an ID of “hero” (or whatever you’d like to use for this). This is done under the “Advanced” tab (see below). You’ll also likely want to give the viewport some height parameters, but I’ll leave that to you.
- In your functions.php file, add the following code, along with the links to your hero images.
function random_hero() { $bg = array('01.jpg', '02.jpg', '03.jpg', '04.jpg', '05.jpg' ); $i = rand(0, count($bg)-1); $selectedBg = "$bg[$i]"; echo '<style type="text/css">'; echo '#hero {'; echo 'background: url('; echo $selectedBg; echo ') no-repeat; }'; echo '</style>'; } add_action( 'wp_head', 'random_hero' );
Homepage only option:
In the code below, I’m targeting only the homepage which will keep all of these big images from loading on all of the pages of the site. Note the “is_front_page()
” below:
function random_hero() { if(is_front_page()){ $bg = array('01.jpg', '02.jpg', '03.jpg', '04.jpg', '05.jpg' ); $i = rand(0, count($bg)-1); $selectedBg = "$bg[$i]"; echo '<style type="text/css">'; echo '#hero {'; echo 'background: url('; echo $selectedBg; echo ') no-repeat; }'; echo '</style>'; } } add_action( 'wp_head', 'random_hero' );
- In your CSS, you can further modify the treatment of your background image by doing something like this:
#hero { background-size: cover; background-position: center center; background-repeat: no-repeat; }
Optional Fade In Animation
If you want to make things a bit more smooth loading, you can add a “fade-in
” class to the same section (just below ID) and add this to your CSS:
.fade-in { animation: fadeIn 2s; -webkit-animation: fadeIn 2s; -moz-animation: fadeIn 2s; -o-animation: fadeIn 2s; -ms-animation: fadeIn 2s; } @keyframes fadeIn { 0% {opacity:0;} 100% {opacity:1;} } @-moz-keyframes fadeIn { 0% {opacity:0;} 100% {opacity:1;} } @-webkit-keyframes fadeIn { 0% {opacity:0;} 100% {opacity:1;} } @-o-keyframes fadeIn { 0% {opacity:0;} 100% {opacity:1;} } @-ms-keyframes fadeIn { 0% {opacity:0;} 100% {opacity:1;} }
Sources/Resources:
- YOOtheme Pro
- Optimize your images at TinyPNG or by similar means
- A portion of this code is from the article at CSS-Tricks
- The “functions.php” file and the “is_front_page()” function (The WordPress Code Reference)
- The CSS background property (W3Schools)
What do you think?