The get_random_header_image() WordPress PHP function returns a random header image URL from the registered images in the theme.
Usage
echo get_random_header_image();
Output:
https://example.com/wp-content/uploads/2023/05/random-header-image.jpg
Parameters
- None
More information
See WordPress Developer Resources: get_random_header_image
Examples
Display a random header image on your site
Set a random header image as the background of the header section.
<header style="background-image: url('<?php echo get_random_header_image(); ?>');"> ... </header>
Create an img tag with a random header image
Output an img tag with the random header image as its source.
<img src="<?php echo get_random_header_image(); ?>" alt="Random Header">
Add a random header image as a CSS background in a style tag
Inject a random header image as a background image in a style tag.
<style> header { background-image: url('<?php echo get_random_header_image(); ?>'); } </style>
Create a custom function to display a random header image with a fallback
Create a function that displays a random header image, but if there are no registered header images, it displays a default image.
function my_theme_random_header_image() { $random_header = get_random_header_image(); if ( $random_header ) { return $random_header; } else { return get_template_directory_uri() . '/images/default-header.jpg'; } }
<img src="<?php echo my_theme_random_header_image(); ?>" alt="Random Header">
Refresh the header image on page reload
Use JavaScript to refresh the random header image when the page is reloaded.
<header id="header" style="background-image: url('<?php echo get_random_header_image(); ?>');"> ... </header> <script> document.addEventListener('DOMContentLoaded', function() { document.getElementById('header').style.backgroundImage = 'url(<?php echo get_random_header_image(); ?>)'; }); </script>