WordPress.org

Support

Support » Plugins and Hacks » Hacks » list url to the first image attached to each post

list url to the first image attached to each post

  • I am trying to list the url to the first image attached to each post. The code im using outputs the images with <img> tags… Even with 'return_html' => 'false'

    Here is what I have so far:

    <?php
    function postimage($size=thumbnail) {
    if ( $images = get_children(array(
    'post_parent' => get_the_ID(),
    'post_type' => 'attachment',
    'numberposts' => 1,
    		'order' => 'ASC',
    		'orderby' => 'ID',
    'post_mime_type' => 'image',
        'return_html' => 'false',)))
    {
    foreach( $images as $image ) {
    $attachmenturl=wp_get_attachment_url($image->ID);
    $attachmentimage=wp_get_attachment_image( $image->ID);
    
    echo $attachmentimage;
    
    }
    } else {
    echo "No Image";
    }
    }
    
    if (have_posts()) :
    while (have_posts()) : the_post();
    
    // List the images
    echo postimage('thumbnail');
    
    endwhile;
    else : ?>
    <div class="entry">
    		<h2>Not Found</h2>
    		Sorry, but you are looking for something that isn't here.
    </div>
    	<?php endif; ?>

    Please help.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Hello,

    Maybe this code could help you, it is a work around to a list with the first image of each post:

    wpworks.wordpress.com/2011/02/01/display-wordpress-post-list-with-custom-size-thumbnails/

    I hope so,

    Best regards,

    Alvaro

    The code im using outputs the images with <img> tags…

    What do you want it to return?

    I would like a list or an array of each image url ex: http://www.iwishihadthis.com/wp-content/uploads/2011/01/47586-hi-FW11-3.jpg

    I am trying to make a plugin that uses ImageMagick to create web banners with the latest content. So far my code requires the absolute path to each image.

    Your said in your opening post that you only wanted the first image, why would you need an array or list for a single image?

    That said, if you do only want the first image’s URL, something simple like this will do the trick.

    function postimage( $echo = true ) {
    	$image = get_children( array(
    		'post_parent' => get_the_ID(),
    		'post_type' => 'attachment',
    		'numberposts' => 1,
    		'order' => 'asc',
    		'orderby' => 'ID',
    		'post_mime_type' => 'image',
    	) );
    	$image_url = ( $image ) ? wp_get_attachment_url( current($image)->ID ) : "No Image";
    	if( $echo )
    		echo $image_url;
    	else
    		return $image_url;
    }

    zakir-devstars
    Member

    @zakir-devstars

    whats the code to get all the images from gallery of post? then i will use the image uRL to pass to one function which will display images in a slideshow.

    thanks in advance!

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘list url to the first image attached to each post’ is closed to new replies.