Site logo

[Resolved] Random background image in element: Block – Page Hero

Home Forums Support [Resolved] Random background image in element: Block – Page Hero

Home Forums Support Random background image in element: Block – Page Hero

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #2275806
    Marc

    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

    #2275893
    David
    Staff
    Customer Support

    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);
    }
    #2275900
    Marc

    My word, you guys are amazing! 😀
    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

    #2275942
    David
    Staff
    Customer Support

    Well thats made my day 🙂 Glad to be of help

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