尝试以下操作:
$args = array(
\'name\'=>\'header-images\',
\'posts_per_page\' => 4,
\'orderby\' => \'rand\'
);
即使用
posts_per_page
而不是
numberposts
如果要使用
query_posts()
根据Codex页面:
http://codex.wordpress.org/Function_Reference/query_posts
Edit:
以下是一个想法-使用给定的slug从页面内容中获取库短代码ID:
/*
* Get an array of the gallery shortcode ids from a page content with a given slug
* @param string $slug Post slug.
* @param string $type Post type.
* @return array Array of the exploded 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;
}
用法示例:
假设我们有一页有鼻涕虫my-gallery-demo
内容中有这样一个短代码:
[gallery ids="1376,1375,341,213,211,210,209,208,206,205"]
要显示
4
随机的
thumb
通过此短代码中的图像,我们执行以下操作:
// initial values:
$slug=\'my-gallery-demo\'; // EDIT post/page slug that contains the gallery shortcode
$type=\'page\'; // EDIT post type (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>\';