Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am using this code directly from the codex.

function echo_first_image ($postID)
{                   
    $args = array(
    'numberposts' => 1,
    'order'=> 'ASC',
    'post_mime_type' => 'image',
    'post_parent' => $postID,
    '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 '<img src="'.wp_get_attachment_thumb_url( $attachment->ID ).'" class="current">';

        }
    }
}

I call it within the loop like this echo_first_image ($post->ID);

The function does call but nothing gets output ... as far as I can see there is nothing in $attachments

I do have an image in the post I am using. It's not a featured image or in a gallery, just in the post.

Am I doing something wrong, or is there something wrong with the code in the first place?

share|improve this question

3 Answers 3

up vote 7 down vote accepted

If you want display a imagem inserted into your content (link to a image, for instance), you must use a function like this (source):

add in functions.php:

function catch_that_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];

  if(empty($first_img)){ //Defines a default image
    $first_img = "/images/default.jpg";
  }
  return $first_img;
}

Then place <?php echo catch_that_image() ?> where you want display the image.

Note: an image just placed in your content can't be set as Featured Image, a bultin WordPress'feature.

share|improve this answer
    
Yes I've seen that code around ... seems like a bit of a hack, you'd think there'd be a "WordPress" way ... I wonder why I need to use preg_match when the codex says you can do it as I posted above. That's my question really to be honest. Is the code that I posted wrong? ... more-so than trying to get it working really. But thanks I may end up having to use this. I don't understand the significance of "an image just placed in your content can't be set as Featured Image". Does that impact upon this in some way. I am just trying to display the first image from the post, not the featured image. –  byronyasgur Jul 31 '12 at 19:06
    
There's a big difference between place an image link inside your post/page content and attach an image. You can attach an image without displaying it at all. Codex example is about getting a file attached to your post/page, there's no way to get a image placed inside by linking, also hotlinking is not a feature WP will deal with without PHP regex. –  Diana Jul 31 '12 at 22:52
    
About the COdex reference: as you can see the doc is called after the function name get_childre, an attachment is a children post so this example only can work for attached content. –  Diana Jul 31 '12 at 23:01
    
Yes I know I can attach an image without inserting it, that bit is clear ... but I don't see how you can insert an image without attaching it ... when I press upload/insert, upload a file from my computer and press insert into post and update then go to media library library it tells me that the image I uploaded is "attached" to the post ? ... or are we talking semantics here because I understand what you're saying about that bit of code only working for attached images. –  byronyasgur Aug 1 '12 at 0:01
    
You can hotlink an image file anywhere. When clicking Insert Image/Media, there's a tab "From URL", where you inform an image URL, i.e. imageshack service. The regex will be able to get this image ("as is"), but WP will not be able to use this image as Featured Image, for instance. –  Diana Aug 1 '12 at 2:37

the code seems perfectly safe. like you said, you don't have any image attached to the post.

Consider going to the media admin panel and attach a image to that post.

Alternately, scrap the post content with a regex for images in it.

share|improve this answer
    
Do I have a misunderstanding of what "attached" means exactly? .... I DO have an image in the post ... is it not attached when you click 'add to post'? –  byronyasgur Jul 31 '12 at 19:04
1  
from your question, it seemed that you typed the html code linking to a image not necessarily attached by wp. –  peteroak Aug 1 '12 at 2:57

I suggest two ways:

Using a Plugin

I would consider using the Get The Image plugin, so you could do something like:

$args = array(
    'post_id' => <id>
    'image_scan' => true
);
get_the_image($args);

The above will try to do things in this order:

  1. Look for the post thumbnail
  2. Look for the first attached image
  3. Scan the post content for a inserted image.

Building support in your theme

However, I'm using a function in a plugin that implements the first two items of the list above.

function gpi_find_image_id($post_id) {
    if (!$img_id = get_post_thumbnail_id ($post_id)) {
        $attachments = get_children(array(
            'post_parent' => $post_id,
            'post_type' => 'attachment',
            'numberposts' => 1,
            'post_mime_type' => 'image'
        ));
        if (is_array($attachments)) foreach ($attachments as $a)
            $img_id = $a->ID;
    }
    if ($img_id)
        return $img_id;
    return false;
}

You can adapt it to also match the third item within Diana's snippet:

function find_img_src($post) {
    if (!$img = gpi_find_image_id($post->ID))
        if ($img = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches))
            $img = $matches[1][0];
    if (is_int($img)) {
        $img = wp_get_attachment_image_src($img);
        $img = $img[0];
    }
    return $img;
}

Just stick these two functions in your functions.php file and use them in the loop like:

<?php while (have_posts()) : the_post(); ?>
    <?php if ($img_src = find_img_src($post) : ?>
        <img src="<?php echo $img_src; ?>" />
    <?php endif; ?>
<?php endwhile; ?>
share|improve this answer
    
Theme is to be for sale commercially so I don't want to tell the end user they have to install a plugin, but thanks. –  byronyasgur Jul 31 '12 at 19:11
    
@byronyasgur Edited the answer to clarify that I gave you two solutions. You don't need to install a plugin to follow the second one. –  vmassuchetto Jul 31 '12 at 21:41
    
thanks I wasn't sure. Will look at that now –  byronyasgur Jul 31 '12 at 23:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.