Reputation: 6509
I have the following PHP to loop through images in my WordPres
function marty_get_images($post_id) {
global $post;
$thumbnail_ID = get_post_thumbnail_id();
$images = get_children( array('post_parent' => $post_id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') );
if ($images) :
foreach ($images as $attachment_id => $image) :
if ( $image->ID != $thumbnail_ID ) :
$img_title = $image->post_title; // title.
$img_caption = $image->post_excerpt; // caption.
$img_description = $image->post_content; // description.
$img_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true); //alt
if ($img_alt == '') : $img_alt = $img_title; endif;
$big_array = image_downsize( $image->ID, 'large' );
$big_img_url = $big_array[0];
$thumb_array = image_downsize( $image->ID, 'thumbnail' );
$thumb_img_url = $thumb_array[0];
?>
<a href="<?php echo $big_img_url; ?>" class="thumb"><img src="<?php echo $thumb_img_url; ?>" alt="<?php echo $img_alt; ?>" title="<?php echo $img_title; ?>" /></a>
<?php endif; ?>
<?php endforeach; ?>
<?php endif;
}
I'd like to just loop once. What do I change in my script?
Upvotes: 0
Views: 3562
Reputation: 38
Better to use array_slice and run the loop once
foreach (array_slice($images,0,1 )as $attachment_id => $image) {
}
here, 0 = index form where loop start, 1 = run the loop once
Upvotes: 1
Reputation: 890
For only one iteration you can use "LIMIT" on query which will return only one record from database
$images = get_children( array('post_parent' => $post_id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID', 'limit' => '1') );
And for only one iteration for condition match
if ( $image->ID != $thumbnail_ID ) :
you can add break; before
Break;
<?php endif; ?>
<?php endforeach; ?>
which will check for one condition match for thumbnail
Upvotes: 1
Reputation: 961
Add break;
after your HTML link. This will break out of the foreach
loop and continue executing any other code which may be after the loop.
http://php.net/manual/en/control-structures.break.php
<?php break; ?>
Upvotes: 1