[Resolved] Random featured image on home page

Home Forums Support [Resolved] Random featured image on home page

Home Forums Support Random featured image on home page

Viewing 13 posts - 1 through 13 (of 13 total)
  • Author
    Posts
  • #1827871
    Jim

    I want random featured images on the home page only. I know there are a gazillion topics on random images, and I feel like I’ve read all of them, but can’t make headway. Many talk about page header background images, and I’m not sure what that is, but doesn’t sound like featured image. I thought I finally found what I needed in one topic and came up with the following in functions.php:

    add_filter( 'generate_page_hero_background_image_url', function( $url ) {
        if ( is_front_page() ) {
    		$headers = array(
    			'https://staging1.forestpathology.org/wp-content/uploads/2020/09/Phoradendron_juniperinum_close_07_FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2019/09/hazard_saguaro_FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2018/06/R37_onnia_root_2_FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2018/06/Annosus-decayed-white-fir-S.-Ute-branch-traces_FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2018/02/aspen_elk_bark_alpine3-FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2017/12/frost-dmg-pipu-2012_3-FI-1.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2017/12/Gymnosporangium_inconspicuum_Amelanchier_01_FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2017/12/Gymnosporangium_common_juniper_2_FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2017/12/PhaeolusImbricate2-FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2019/11/R37_onnia_armillaria_7_FI2.jpg'
    		);
    
    		$url = $headers[ rand( 0, count( $headers ) -1 ) ];
            return $url;
        }
    
        return $url;
    } );

    That did nothing, and when I found out there’s no hook called ‘generate_page_hero_background_image_url’, I could see why. It seems such code was recommended in the context of Elements. I tried to use that to create such a hook but it had no effect either. Frankly I’ve never really been able to wrap my head around Elements and would prefer a code solution.

    Is there one? And if not, what do I need to do with Elements to make it work?

    #1827986
    David
    Staff
    Customer Support

    Hi there,

    that code will work if you’re using a Header Element on your front page:

    https://docs.generatepress.com/article/header-element-overview/

    First set up the header element to make sure it displays for example follow these settings:

    1. Add new Header Element.
    2. In the Elements Text Area add a HTML Comment eg. <!-- Featured Header Element --> or some HTML if you want to display Text over the featured image.
    3. Increase the Header Elements Top and Bottom Padding to give it some height.
    4. Set the Background Image to Featured Image – and a background color as a fallback.
    5. Set the Display Rules to Front Page.

    Then apply the code you have above.

    #1827998
    Jim

    Thanks. Now just to be clear, since I specify the front page in the Elements GUI, should I remove the if ( is_front_page() ) { as well as the second return $url;

    Also, when you say “apply the code”, is that in functions.php or in the Elements GUI?

    And, I assume by implication there is no pure code solution?

    #1827999
    David
    Staff
    Customer Support

    That code goes in your functions.php and you would keep it exactly as it is.

    Alternatively you can just a hook in a random image – no header element required. Heres an example snippet based on the above array:

    add_action( 'generate_after_header', function() {
        if ( is_front_page() ) {
    		$headers = array(
    			'https://staging1.forestpathology.org/wp-content/uploads/2020/09/Phoradendron_juniperinum_close_07_FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2019/09/hazard_saguaro_FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2018/06/R37_onnia_root_2_FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2018/06/Annosus-decayed-white-fir-S.-Ute-branch-traces_FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2018/02/aspen_elk_bark_alpine3-FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2017/12/frost-dmg-pipu-2012_3-FI-1.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2017/12/Gymnosporangium_inconspicuum_Amelanchier_01_FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2017/12/Gymnosporangium_common_juniper_2_FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2017/12/PhaeolusImbricate2-FI.jpg',
    			'https://staging1.forestpathology.org/wp-content/uploads/2019/11/R37_onnia_armillaria_7_FI2.jpg'
    		);
    
    		$url = $headers[ rand( 0, count( $headers ) -1 ) ];
    		printf( 
    		'<img width="1024" height="800" src="%1$s" alt="your alt text" />',
    		$url
    		);
        }
    } );
    #1828738
    Jim

    Thank you so much David, that generate_after_header code works perfectly.

    #1828953
    David
    Staff
    Customer Support
    #2265975
    Elvis

    Hello David,
    I am using this code to have a random bg image header on the homepage:

    add_filter( 'generate_page_hero_background_image_url', function( $url ) {
    	if (  is_front_page()  ) {
    		$headers = array(
    			esc_url(get_field('apuri_home_random_1', )),
    			esc_url(get_field('apuri_home_random_2', )),
    			esc_url(get_field('apuri_home_random_3', )),
    			esc_url(get_field('apuri_home_random_4', )),
    			esc_url(get_field('apuri_home_random_5', )),
    			esc_url(get_field('apuri_home_random_6', )),
    			esc_url(get_field('apuri_home_random_7', )),
    			esc_url(get_field('apuri_home_random_8', )),
    			esc_url(get_field('apuri_home_random_9', )),	
    			esc_url(get_field('apuri_home_random_10' ))
    		);
    		// remove empty values from array
    		$headers = array_values( array_filter( $headers ) );
    			$url = $headers[ rand( 0, count( $headers ) -1 ) ] . '?cache_buster=' . rand( 0, 999999999); 
    			return $url;
    		}
    	}
    );

    This works perfect on Homepage. However it brakes all other hero headers I want to have static image only.

    I had first been using ACF options page to store the image fields, then when I saw it randomizes all header images on any page that has a hero element (not the same one, but the same type) that have generatepress header element I moved the same set of fields on the homepage and added the is_front_page condition. However, now other hero sections have no image at all.

    Is this expected behavior?
    Is it possible some image data has remained in options table and its now messing up other headers?
    Any pointers as to how to solve this.

    Thank you so much for any help.
    Best,
    Elvis

    To understand recursion, you first have to understand recursion.

    #2265998
    David
    Staff
    Customer Support

    Hi there,

    you need to return $url; outside of the IF condition, otherwise it won’t return anything if the condition isn’t met.

    #2266018
    Elvis

    Omg,
    this was a much simpler solution then I anticipated. 🙂

    This it my code now, and works as expected:

    add_filter( 'generate_page_hero_background_image_url', function( $url ) {
    	$headers = array(
    		esc_url(get_field('apuri_home_random_1', 'option' )),
    		esc_url(get_field('apuri_home_random_2', 'option' )),
    		esc_url(get_field('apuri_home_random_3', 'option' )),
    		esc_url(get_field('apuri_home_random_4', 'option' )),
    		esc_url(get_field('apuri_home_random_5', 'option' )),
    		esc_url(get_field('apuri_home_random_6', 'option' )),
    		esc_url(get_field('apuri_home_random_7', 'option' )),
    		esc_url(get_field('apuri_home_random_8', 'option' )),
    		esc_url(get_field('apuri_home_random_9', 'option' )),	
    		esc_url(get_field('apuri_home_random_10', 'option'))
    	);
    	// remove empty values from array
    	if (  is_front_page()  ) {
    		$headers = array_values( array_filter( $headers ) );
    			$url = $headers[ rand( 0, count( $headers ) -1 ) ] . '?cache_buster=' . rand( 0, 999999999); 
    			return $url;
    		} else {
    			return $url;
    		}
    	}
    );

    To understand recursion, you first have to understand recursion.

    #2266568
    David
    Staff
    Customer Support
    #2316281
    Elvis

    I wish to share a solution that extends this a bit, to prevent random image bg to be cached.
    The above random hero image solution works nice, BUT since I moved the site to a litespeed server (which flies BTW) the above solution stopped working as litespeed caches the html. Perhaps its possible to exclude that part of the page from caching, but I havent managed to figure it out.

    But If the randomization moves to JS then I can keep the cache and keep the ACF UI to pick images to randomize.
    This is the complete solution.

    /**
     * Function that returns max 10 images as header background
     * Sends to JS as an array of images, then in JS picks one image on random
     * We are doing it this way to try avoid cacnhing background image as part of html
     */
    function apuri_random_images_via_js( $url ) {
    	$images = array(
    		esc_url(get_field('apuri_home_random_1', 'option' )),
    		esc_url(get_field('apuri_home_random_2', 'option' )),
    		esc_url(get_field('apuri_home_random_3', 'option' )),
    		esc_url(get_field('apuri_home_random_4', 'option' )),
    		esc_url(get_field('apuri_home_random_5', 'option' )),
    		esc_url(get_field('apuri_home_random_6', 'option' )),
    		esc_url(get_field('apuri_home_random_7', 'option' )),
    		esc_url(get_field('apuri_home_random_8', 'option' )),
    		esc_url(get_field('apuri_home_random_9', 'option' )),	
    		esc_url(get_field('apuri_home_random_10', 'option'))
    	);
    	if (  is_front_page()  ) {
    		$images = array_values( array_filter( $images ) );
    		?>
    			<script type="text/javascript" id="random-images">
    			    var imageArray = <?php echo json_encode($images); ?>;
    					document.querySelector('.page-hero').style.background = 'url(' + imageArray[Math.floor(Math.random() * imageArray.length)] + ')' + ' center center / cover' + ' no-repeat';
    			 </script>
    			<style id="random-images">
    				.page-hero {
    					position: relative;
    				}
    				.page-hero:after {
    					content: "";
    					position: absolute;
    					top: 0;
    					bottom: 0;
    					left: 0;
    					right: 0;
    					width: 100%;
    					height: 100%;
    					padding: 0;
    					margin: 0;
    					background-color: rgba(0,0,0,0.55) !important;
    					z-index: 0;
    				}
    				.page-hero > .inside-page-hero {
    					position: relative;
    					z-index: 1;
    				}
    				
    			</style>
    		<?php
    	} else {
    		return $url;
    	}
    }
    add_filter( 'wp_footer', 'apuri_random_images_via_js');

    Hope this is useful.

    To understand recursion, you first have to understand recursion.

    #2316381
    David
    Staff
    Customer Support

    Thats great – thanks for sharing that with us !!

    #2316507
    Elvis

    Gladly. Thanks for all of your help.

    To understand recursion, you first have to understand recursion.

Viewing 13 posts - 1 through 13 (of 13 total)
  • You must be logged in to reply to this topic.