Waarten
Waarten

Reputation: 115

Maximum PHP Loops

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

Answers (4)

liquorvicar
liquorvicar

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

mishu
mishu

Reputation: 5397

use the value you need in your $args array for the key numberposts

Upvotes: 1

ceejayoz
ceejayoz

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

Shomz
Shomz

Reputation: 37701

You have to introduce a counter variable and break out of the loop if the variable reaches certain value. Or you could just use the for loop.

Upvotes: 0

Related Questions