最近,我问了一个关于如何从所有帖子中获取所有图片的问题,我得到了一个有效的答案,但不幸的是,代码也得到了帖子thumnbnails,我没有找到限制查询图片数量的方法。
My last question is here.
谢谢
<?php
$query = new WP_Query( array( \'post_type\' => \'post\', \'posts_per_page\' => -1 ) );
if( $query->have_posts() ){
while($query->have_posts()){
$query->the_post();
$thumb_ID = get_post_thumbnail_id( $post->ID );
$image_query = new WP_Query( array( \'post_type\' => \'attachment\', \'exclude\' => $thumbID, \'post_status\' => \'inherit\', \'post_mime_type\' => \'image\', \'posts_per_page\' => -1, \'post_parent\' => get_the_ID() ) );
while( $image_query->have_posts() ) {
$image_query->the_post();
echo \'<dl class="gallery-item"><dt class="gallery-icon"><a rel="shadowbox[sbalbum-1];player=img;" href="\' , the_permalink() , \'">\', wp_get_attachment_image( get_the_ID() ) , \'</a></dt></dl>\';
}
}
}
?>
在image\\u查询中更改posts\\u per\\u page参数的数量对显示的附件数量没有影响。
在@Bainternet的帮助下,我产生了以下工作代码:
<?php
$image_count = 0;
$max_images = of_get_option(\'thumbs_number\');
$Posts = new WP_Query();
$Posts->query(\'post_type=post&post_status=publish&posts_per_page=-1\');
while ($Posts->have_posts()) : $Posts->the_post();
$args = array(
\'post_type\' => \'attachment\',
\'numberposts\' => -1,
\'post_status\' => null,
\'post_parent\' => $post->ID,
\'exclude\' => get_post_thumbnail_id($id)
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
if ($image_count < $max_images){
echo \'<dl class="gallery-item"><dt class="gallery-icon"><a rel="shadowbox[sbalbum-1];player=img;" href="\' , the_permalink() , \'">\';
echo wp_get_attachment_link( $attachment->ID, \'footer_thumbs\' );
echo \'</a></dt></dl>\';
$image_count = $image_count + 1;
}
}
}
endwhile;?>
最合适的回答,由SO网友:Bainternet 整理而成
试试这个:
$image_count = 0;
$max_images = 10; //set this to the max number of images you want.
$ids = get_posts( array( \'post_type\' => \'post\', \'posts_per_page\' => -1 ,\'fields\' =>\'ids\') );
if (count($ids) > 0){
foreach ($ids as $id){
while ($image_count < $max_images){
$args = array(
\'post_type\' => \'attachment\',
\'numberposts\' => -1,
\'post_status\' => null,
\'post_parent\' => $id,
\'exclude\' => get_post_thumbnail_id($id)
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
if ($image_count < $max_images){
echo \'<dl class="gallery-item">
<dt class="gallery-icon">
<a rel="shadowbox[sbalbum-1];player=img;" href="\' . get_permalink($attachment->ID) . \'">\'. wp_get_attachment_image( $attachment->ID ) . \'</a>
</dt>
</dl>\';
$image_count = $image_count + 1;
}
}
}
}
}
}
这与法典中的示例大致相同(
Show All attachments for the current post beside Thumb ) 结合您的代码(几乎)来获取所有帖子的所有附件。
请注意,第一个查询已更改为get_posts()
带参数的函数fields
设置为ids仅获取帖子的ID,因为您实际上不需要其余的数据,而且速度要快得多。