Skip to main content
4 of 6
added 1656 characters in body
birgire
  • 67.8k
  • 7
  • 119
  • 251

Try this:

$args = array(
    'name'=>'header-images',
    'posts_per_page' => 4,  
    'orderby' => 'rand'
);

i.e. use posts_per_page instead of numberposts if you want to use query_posts() according to the the Codex page:

http://codex.wordpress.org/Function_Reference/query_posts

Edit:

Here is one idea - fetch the gallery shortcode ids from a page content with a given slug:

/*
* Get an array of the 'ids' parameter from the gallery shortcode that is placed in the content of a post/page with a given slug. 
* @param string $slug Post slug.  
* @param string $type Post type.  
* @return array Array of the gallery shortcode 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;
}       

Usage example:

We have for example a page with the slug my-gallery-demo and in the content there is this shortcode like this one:

[gallery ids="1376,1375,341,213,211,210,209,208,206,205"]

To display 4 random 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 gallery shortcode 
$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>';
birgire
  • 67.8k
  • 7
  • 119
  • 251