Randomly add a ‘ul’ list of images

I’m developing a photo gallery WP site. I would like to add “ul” list of images that are randomly picked from the gallery.

How would I randomly pick a number of images from the media library.

Read More

Any pointers would be greatly appreciated.

Related posts

Leave a Reply

1 comment

  1. Adding the following to your theme’s functions.php file will let you use a shortcode ( [wpse73055-random-images] ) with an optional num parameter (i.e. [wpse73055-random-images num=5] to display 5 random images).

    function wpse73055_get_random_images( $atts ) {
        extract( shortcode_atts( array(
            'num' => 10
        ), $atts ) );
    
        $args = array(
            'post_type' => 'attachment',
            'post_mime_type' =>'image',
            'post_status' => 'inherit',
            'posts_per_page' => $num,
            'orderby' => 'rand'
        );
        $images_query = new WP_Query( $args );
    
        $images = $images_query->posts;
    
        $output = '<ul>';
        foreach ( $images as $image ) {
            $output .= '<li>' . wp_get_attachment_link( $image->ID ) . '</li>';
        }
        $output .= '</ul>';
    
        return $output;
    }
    add_shortcode( 'wpse73055-random-images', 'wpse73055_get_random_images' );