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.
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' );
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' );
#hero { background-size: cover; background-position: center center; background-repeat: no-repeat; }
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;} }