简体   繁体   中英

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?

You can use the break statement:

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

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; ?>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM