-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrandom-images.php
70 lines (55 loc) · 2.1 KB
/
random-images.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
/**
* Plugin Name: Random Images
* Description: Display a set of random attached images with the [random_images] shortcode.
* Version: 0.7
* Author: Sheri Bigelow
* Author URI: http://designsimply.com/
* License: GPLv2 or later
*/
class Random_Images_Plugin {
static function load() {
add_action( 'init', array( 'Random_Images_Plugin', 'init' ) );
add_action( 'wp_enqueue_scripts', array( 'Random_Images_Plugin', 'enqueue_scripts' ) );
}
static function init() {
add_shortcode( 'random_images', array( 'Random_Images_Plugin', 'random_images' ) );
}
static function random_images( $attr ) {
$attr = shortcode_atts( array(
'size' => 'thumbnail',
'link' => '',
'total' => 6,
), $attr );
$attr['total'] = absint( $attr['total'] );
if ( ! in_array( $attr['total'] , range( 1, 100 ) ) )
$attr['total'] = 6;
if ( ! in_array( $attr['size'], array( 'thumbnail', 'medium', 'large', 'full' ) ) )
$attr['size'] = 'thumbnail';
// In this context, posts_per_page is a max number of results to randomize,
// not the number of results that will be displayed. It's a way of randomizing
// results via PHP while still taking advantage of caching the query first.
$all_attached_images = get_children( 'post_parent=&post_type=attachment&post_mime_type=image&posts_per_page=800&poststatus=publish' );
$random_images = array_rand( $all_attached_images, $attr['total'] );
$c = count( $random_images );
if ( 1 == $c )
$random_images = array ( $random_images );
if ( 0 < $c ) :
$output = '<div class="random-images">';
while ( list( $k, $v ) = each( $random_images ) ) :
if ('file' == $attr['link'] ) :
$link = wp_get_attachment_url( $v );
else :
$link = get_permalink( $v );
endif;
$output .= ' <a href="' . $link . '" title="' . get_the_title( $v ) . '">' . wp_get_attachment_image( $v, $attr['size'] ) . '</a>';
endwhile;
$output .= '</div><!-- #random-images -->';
endif;
return $output;
}
static function enqueue_scripts() {
wp_enqueue_style( 'random-images', plugins_url( 'random-images.css', __FILE__ ) );
}
}
Random_Images_Plugin::load();