michaelmcgurk michaelmcgurk - 1 month ago 6
PHP Question

Run foreach loop just one iteration with PHP

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?

Answer

You can use the break statement:

<?php endif; ?>
<?php break; ?>
<?php endforeach; ?>
Comments