Site logo

Archived topic

Random background image in element: Block - Page Hero

3 replies · Started by Marc on July 7, 2022

Viewing posts 1–4 of 4

Hi there,

At my site I created an element of type Block - Page Hero (quick hook select: after header). It shows up at my front page as you can see here:
https://www.matjoo.nl

Is there a way to show some random background images?

Cheers,
Marc

Hi there,

you could do something like this:

1. Add the following PHP Snippet to your site, and update the array with the different images you want to use:

add_action( 'wp_head', function() {
  if ( is_front_page() ) {
    $headers = array(
      'full_url_to_images/image-1.jpg',
      'full_url_to_images/image-2.jpg',
      'full_url_to_images/image-3.jpg',
      'full_url_to_images/image-4.jpg',
      'full_url_to_images/image-5.jpg'
    );

    $url = $headers[ rand( 0, count( $headers ) -1 ) ];
    printf( 
      '<style>:root {--hero-bg: url(%1$s);}</style>',
      $url
    );
  }
} );

Adding PHP: https://docs.generatepress.com/article/adding-php/

2. we now need some CSS, and we can take advantage of the my-page-hero class you already have. So just add this:

.gb-container.my-page-hero:before {
    background-image: var(--hero-bg);
}

My word, you guys are amazing! :-D
This really works like a charm; no more edits needed!
Hard to believe you give this kind of support.

You just made my day, David, thnx a ton!

Cheers,
Marc

Well thats made my day :) Glad to be of help

This archived topic is closed to new replies.