WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] how to check if its the last image attachment (4 posts)

  1. TheBracketBoy
    Member
    Posted 1 year ago #

    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;
    
    			}
    	}
    }
  2. keesiemeijer
    moderator
    Posted 1 year ago #

    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;
    			}
    		}
    	}
    }
  3. TheBracketBoy
    Member
    Posted 1 year ago #

    many many thanks keesiemeijer!!!

    it works :)

  4. keesiemeijer
    moderator
    Posted 1 year ago #

    You're welcome. I'm glad you got it resolved :-)

Topic Closed

This topic has been closed to new replies.

About this Topic