简体   繁体   中英

Wordpress get first image from a post

Trying to get the first image from a post, but my php code doesn't return anything, any help?

<?php while ($browndog_blog->have_posts()) : $browndog_blog->the_post();                    
    $args = array(
    'numberposts' => 1,
    'post_mime_type' => 'image',
   'post_parent' => $post->ID,
    'post_status' => null,
    'post_type' => 'attachment'
    );

    $attachments = get_children( $args );

    //print_r($attachments);

    if ($attachments) {
        foreach($attachments as $attachment) {
            $image_attributes = wp_get_attachment_image_src( $attachment->ID, 'thumbnail' )  ? wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) : wp_get_attachment_image_src( $attachment->ID, 'full' );

            echo '<a href="'.get_permalink($post->ID).'"><img src="'.wp_get_attachment_thumb_url( $attachment->ID ).'"></a>';
            echo '<p>'.get_the_excerpt($post->ID).'</p>';
            echo '<p><a href="'.get_permalink($post->ID).'">Read More</a></p>';
        }
    }
endwhile; ?>

Not sure what's going wrong as I'm using a similar code to get all of the image attachments and not just one, and that works fine.

get_children() only returns images that have been uploaded directly to that post. If an image has been attached to a given post it will not be considered one it's children and thus wont be returned by the afore mentioned function.

An easy way to check a post's children is login to the dashboard and go to posts, edit post. Click the Add Media button above the editor and from the only drop down box select Uploaded to this post . If this is empty then get_children will not return any images regardless of the post's content.

I think I just did the same thing as you are looking to do... I won't claim to be a guru, but here's what I did to get this working and with any luck you will be able to adapt it to your needs.

$image_id=get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,’large’);
$image_url=$image_url[0];

Basically the first image in the array is the thumbnail, as I understand it, so that's why I grab the thumbnail id first, then use it to retrieve the large version of the image.

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