/*
* Get an array of the 'ids' parameter from the gallery shortcode that is placed in the contentids offrom a post/page content with a given slug.
* @param string $slug Post slug.
* @param string $type Post type.
* @return array Array of the gallery shortcodeexploded ids parameter.
*/
function get_gallery_ids_wpse_87978($slug,$type){
$output=array();
$my_query = new WP_Query(array('name'=>$slug,'post_type'=>$type));
while ($my_query->have_posts()) : $my_query->the_post();
$content=get_the_content();
preg_match('/ids=\"([0-9,]+)\"/i', $content, $matches);
if(isset($matches[1])){
$output = explode(",",$matches[1]); // let's take the last set of ids
}
endwhile;
return $output;
}
WeLet's say we have for example a page with the slug my-gallery-demo
and in the content there is this shortcode like this one:
To display 4
random thumb
images from this shortcode we do the following:
// initial values:
$slug='my-gallery-demo'; // EDIT post/page slug that contains the gallery shortcode
$type='page'; // EDIT post slug that contains the gallerytype shortcode(post,page,...)
$size='thumb'; // EDIT image size (thumb,large,full,...)
$n=4; // EDIT number of random images to show
// fetch all ids from the gallery shortcode:
$ids=get_gallery_ids_wpse_87978($slug,$type);
// get n random keys from the $ids array:
$random_ids=array_rand($ids,$n);
// display a list of n random images:
echo '<ul>';
foreach($random_ids as $random_id){
echo '<li>';
echo wp_get_attachment_image( $ids[$random_id], $size );
echo '</li>';
}
echo '</ul>';