To get a random image from a WordPress server, you can use several approaches, depending on where and how you want to display the image. Here are a few methods:
1. Using PHP and WP_Query
You can use the WP_Query
function to get a random image from the media library:
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_status' => 'inherit',
'orderby' => 'rand',
'posts_per_page' => 1,
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$image_url = wp_get_attachment_url(get_the_ID());
echo '<img src="' . esc_url($image_url) . '" alt="' . esc_attr(get_the_title()) . '">';
}
}
wp_reset_postdata();
This code selects one random image and displays it on the screen.
2. Using JavaScript and REST API
You can create an API request to get a random image and then display it using JavaScript:
fetch('/wp-json/wp/v2/media?per_page=1&orderby=rand')
.then(response => response.json())
.then(data => {
if (data.length > 0) {
const imageUrl = data[0].source_url;
const imageElement = document.createElement('img');
imageElement.src = imageUrl;
document.body.appendChild(imageElement);
}
})
.catch(error => console.error('Error fetching image:', error));
This code makes a request to the WordPress REST API, selects a random image, and adds it to the page.
3. Shortcode for inserting into a post or page
You can create a shortcode to insert a random image into a post or page:
function random_image_shortcode() {
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_status' => 'inherit',
'orderby' => 'rand',
'posts_per_page' => 1,
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$image_url = wp_get_attachment_url(get_the_ID());
return '<img src="' . esc_url($image_url) . '" alt="' . esc_attr(get_the_title()) . '">';
}
}
wp_reset_postdata();
}
add_shortcode('random_image', 'random_image_shortcode');
Now you can insert [random_image]
into any post or page, and WordPress will output a random image.
4. Using Plugins
If you prefer not to write code, there are plugins that can automatically display random images. For example:
- Random Image Widget
- Advanced Random Posts Widget
Choose the suitable method based on your requirements and access level to the WordPress code.