我已经安装了这个插件(http://wordpress.org/plugins/media-categories-2/) 对我的图像进行分类。
在我的功能中。php我编写了以下代码来限制库中显示的图像数量:
function get_random_gallery_images(){
global $wpdb,$post;
$ids = "";
$counter = 0;
$number_of_posts = 1;
$args = array(
\'post_type\' => \'attachment\',
\'numberposts\' => 1,
\'post_status\' => null,
\'orderby\' => \'rand\',
\'post_parent\' => $post->ID
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
if ($counter != 0) {
$ids .= \',\'.$attachment->ID;
}
else {
$ids .= $attachment->ID;
}
$counter++;
}
}
return $ids;
}
在我的单曲里。php我输入了以下代码:
$attachment_ids = get_random_gallery_images();
$category_current = get_the_category($post->ID) ; //for getting the images of that specific category
echo do_shortcode(\'[gallery columns="1" category="\'.$category_current[0]->name.\'" include="\'.$attachment_ids.\'" link="file"]\');
问题是,如果我更改numberposts的值,这并不重要。它始终显示所有图像。我做错了什么?我只想显示1个图像。
SO网友:Maruti Mohanty
使用posts_per_page
而不是numberposts
所以$args
对于get_posts
如下所示,以及的参数post_status
是错误的。有关详细信息,请查看法典here
此外,当您获取一个附件时,为其设置计数器也是无用的。您可以使用修改后的函数
function get_random_gallery_images(){
global $wpdb, $post;
$args = array(
\'post_type\' => \'attachment\',
\'posts_per_page\' => 1,
\'post_status\' => \'any\',
\'orderby\' => \'rand\',
\'post_parent\' => $post->ID
);
$attachments = get_posts( $args );
if ($attachments) {
foreach ( $attachments as $attachment ) {
$ids = $attachment->ID;
}
}
return $ids;
}
有关更多详细信息,请查看
codex