• Hi,
    I got an image loader, that I display like below in my php :

    <?php
    $images = get_post_meta( $post->ID, 'photos_flat' );
    
    if ( $images ) {
    printf( '<div id="slider">' );
        foreach ( $images as $attachment_id ) {  
    
            $thumb = wp_get_attachment_image( $attachment_id, 'thumbnail' );
            $full_size = wp_get_attachment_url( $attachment_id );
    
            printf( '<div class="img"><a href="%s">%s</a></div>', $full_size, $thumb );
        }
    
    printf( '</div>' );
    }
    
    ?>

    I want to display only the first image from the post, is there an easy way ? I’ve tried a bunch of things, but can’t find a valid solution …
    I’m a bit lost with it …

    Thanks,

Viewing 4 replies - 1 through 4 (of 4 total)
  • SOURCE :
    https://wordpress.stackexchange.com/questions/60245/get-first-image-in-a-post

    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;
    }

    and

    <?php while (have_posts()) : the_post(); ?>
    <?php if ($img_src = find_img_src($post) : ?>
    <img src=”<?php echo $img_src; ?>” />
    <?php endif; ?>
    <?php endwhile; ?>

    Thread Starter alguna

    (@alguna)

    Thanks gotgotf,

    But as I’m loading the images with a custom field in the post (‘photos_flat’), I can only display them with the code mentioned above, so when I try to display only the first of it, the code you tell me is not working unfortunatly …

    instead of foreach, I would like to say for the first …

    Thanks in advance,

    Maybe with $thumb[0]

    OR SOURCE /
    https://stackoverflow.com/questions/15978879/get-first-image-on-custom-post-type
    function catch_that_image($my_postid) {
    global $post;

    $first_img = ”;
    ob_start();
    ob_end_clean();
    $output = preg_match_all(‘/<img.+src=[\'”]([^\'”]+)[\'”].*>/i’, get_post_field(‘post_content’, $my_postid), $matches);

    $first_img = $matches [1] [0];

    // no image found display default image instead
    if(empty($first_img)){

    $first_img = “/images/default.jpg”;
    }
    return $first_img;
    } ?>

    <div class=”thumbnail”>
    <?php echo catch_that_image($loop->ID) ?>
    </div>

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘first image only’ is closed to new replies.