WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] how to check if its the last image attachment

[Resolved] how to check if its the last image attachment

  • hi,

    can somebody help?
    i want to check if it is the last image attachment inside the for each loop… thanks!

    here is the code…

    function my_attachments_url($size = thumbnail) {
    
    	if($images = get_children(array(
    		'post_parent'    => get_the_ID(),
    		'post_type'      => 'attachment',
    		'numberposts'    => -1, // show all
    		'post_status'    => null,
    		'post_mime_type' => 'image',
    	))) {
    		foreach($images as $image) {
    			$myau_url   = wp_get_attachment_url($image->ID);
    			$myau_img   = wp_get_attachment_image($image->ID,$size);
    
    			// display only the attachment url
    			echo $myau_url;
    
    			//i want to check if its the last image, and if it is, i want to display the image
    			echo $myau_img;
    
    			}
    	}
    }
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator keesiemeijer

    @keesiemeijer

    Maybe with a counter:

    function my_attachments_url($size = 'thumbnail') {
    
    	if($images = get_children(array(
    		'post_parent'    => get_the_ID(),
    		'post_type'      => 'attachment',
    		'numberposts'    => -1, // show all
    		'post_status'    => null,
    		'post_mime_type' => 'image',
    	))) {
    		$i = 0;
    		$image_count = count($images);
    		foreach($images as $image) {
    			++$i;
    			$myau_url   = wp_get_attachment_url($image->ID);
    			$myau_img   = wp_get_attachment_image($image->ID,$size);
    
    			// display only the attachment url
    			echo $myau_url;
    
    			//i want to check if its the last image, and if it is, i want to display the image
    			if($i == $image_count) {
    			  echo $myau_img;
    			}
    		}
    	}
    }

    many many thanks keesiemeijer!!!

    it works 🙂

    Moderator keesiemeijer

    @keesiemeijer

    You’re welcome. I’m glad you got it resolved 🙂

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘[Resolved] how to check if its the last image attachment’ is closed to new replies.
Skip to toolbar