Reputation: 115
How can I set a maximum of times the loop gives an output (I tried with a while loop, but didn't get it working)?
function show_random_thumbs() {
$args = array(
'orderby' => 'rand',
'post_type' => 'attachment',
'post_parent' => null,
'post_mime_type' => 'image',
'post_status' => 'published',
'numberposts' => -1,
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
echo '<a href="';
echo get_permalink($attachment->post_parent);
echo '" title="';
echo get_the_title($attachment->post_parent);
echo '">';
$title = get_the_title($attachment->post_parent);
echo wp_get_attachment_image($attachment->ID, 'thumbnail', false, array('title' => $title) );
echo '</a>';
}
}
}
Upvotes: 0
Views: 1031
Reputation: 6106
Why don't you limit the size of the array you're looping through:
$attachments = get_posts($args);
if ($attachments) {
$attachmentsToDisplay = array_slice( $attachments, 0, 50 );
foreach ($attachmentsToDisplay as $attachment) {
etc...
}
}
Also not sure what your get_posts() function does but you might want to check $attachments is actually an array before the foreach loop.
Upvotes: 1
Reputation: 179994
Have a counter variable and break
when it exceeds a certain level.
$count = 0;
foreach($array as $element) {
$count++;
// do stuff
if($count == 10) {
break;
}
}
Upvotes: 2