How to get random image in php, wordpress

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.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

Why Files with Identical Content (*.js, *.php, *.css) Can Have Different Sizes?

When developers compare files with identical content but notice that their sizes differ, it can be perplexing. Let’s explore why this happens and what factors influence the size of files with extensions like *.js, *.php, and *.css. 1. File Encoding One of the key factors affecting file size is text encoding. The most common encodings…
Read more

How to transfer a site from dle to WordPress?

Transferring a website from DLE (DataLife Engine) to WordPress can be a complex process, especially if the site has a lot of content. Here’s a step-by-step guide: 1. Preparation 2. Export Data from DLE DLE uses its own database structure, so you’ll need to export data and convert it into a format compatible with WordPress:…
Read more