Advertisement
Guest User

Untitled

a guest
Jul 26th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.17 KB | None | 0 0
  1. /*
  2.  * Extract a random image from the last 3 in a post gallery
  3.  *
  4.  * @param string $size the image size . default to thumbnail default WP size
  5.  * @return array image data or false.
  6.  */
  7.  
  8. if ( ! function_exists( 'get_rand_img_from_post_gallery' ) ){
  9.     function get_rand_img_from_post_gallery($size = 'thumbnail') {
  10.         global $post;
  11.         $retarray = array();
  12.         $images = get_children(array(
  13.             'post_parent'    => $post->ID,
  14.             'post_type'      => 'attachment',
  15.             'numberposts'    => -1, // show all
  16.             'post_status'    => null,
  17.             'post_mime_type' => 'image',
  18.             'orderby'                => 'menu_order',
  19.             'order'                  => 'DESC'
  20.         ));
  21.         if (is_array($images) && count($images)>0){
  22.             //preserve associative array keys: php > 5.0.2 only!!!
  23.             $last_three_images= array_slice($images,0,3,true);
  24.             $random = $last_three_images[array_rand($last_three_images,1)];
  25.             $retarray['id'] = $random->ID;
  26.             $retarray['imgtag'] = wp_get_attachment_image($random->ID,$size);
  27.             $retarray['post-link'] = get_permalink($random->post_parent);
  28.             $retarray['title'] = apply_filters('the_title',$random->post_title);
  29.             return $retarray;
  30.         }else{
  31.             //no images found
  32.             return false;
  33.         }
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement