logo
Ask your WordPress questions! Pay money and get answers fast! (more info)

Warning: Please do not give out any FTP or ssh credentials to anyone, unless you trust them completely. Giving out login details is dangerous.

If the asker does not get an answer then they have 10 days to request a refund.

$25
Grab First Post Image and Ignore Embeded Images

In my custom theme, I added functionality to automatically grab the first image of a post and display it on the main blog page.

The problem that it displays both the thumbnail and the embedded image.

Here's the code I used...
function first_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;
}


To display it I used this...
			<img src="<?php echo first_image() ?>" alt="<?php the_title(); ?>" class="postthumbnail" />
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<?php the_content(__('Read More Here...'));?>


The other issue I have is that the code above displays a DEFAULT IMAGE if not first image is found, I want to display NOTHING if no image is found in the post.

This question has been answered.

Armand Morin | 12/30/10 at 1:21am Edit


(4) Possible Answers Submitted...

See a chronological view of answers?

Warning: Please do not give out any FTP or ssh credentials to anyone, unless you trust them completely. Giving out login details is dangerous.

  • avatar
    Last edited:
    12/30/10
    1:40am
    akosipau says:

    1. it display both thumbnail and embedded image because you put the image calling the first_image function at the top of the_content function.

    2. below:

    if(empty($first_img)){ //Defines a default image

    $first_img = "";

    }
    return $first_img;


    or

    if(!empty($first_img)){
    return $first_img;
    }

    • 12/30/10 2:26am

      Armand Morin says:

      I don't understand your answer in Part 1. I moved the call to the function after the_content function and it makes no difference. Just the fact the image is now called after the post content.

      I tried the $first_img = ""; idea before, but the code still displays the IMG tags for the call to an image. So I have just broken image displayed.

    • 12/30/10 2:35am

      akosipau says:

      1. means, it display both cause you both called the img with first_image function on it and the_content function where it contain the image called in first_image function.

      2. because you put the raw img on your code and only appear as image if first_image return a url image.

      to fix that..

      ORIGINAL:

      <img src="<?php echo first_image() ?>" alt="<?php the_title(); ?>" class="postthumbnail" />
      <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>

      <?php the_content(__('Read More Here...'));?>


      SHOULD BE:
      <?php if(first_image() <> '') : ?>
      <img src="<?php echo first_image() ?>" alt="<?php the_title(); ?>" class="postthumbnail" />
      <?php endif; ?>
      <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
      <?php
      if(is_single()) {
      the_content(__('Read More Here...'));
      } else {
      the_excerpt(__('Read More Here...'));
      }
      ?>


      and your first_image function should be:

      ORIGINAL:
      function first_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;

      }


      SHOULD BE:
      function first_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 = "";

      }

      return $first_img;

      }


  • avatar
    Last edited:
    12/30/10
    1:53am
    Rashad Aliyev says:

    I'll give you other solution: Via a little plugin. Save it for example like this myfistimage.php and install like a plugin. (you can put it your plugin directory and activate or you can upload as .zip file)

    using code for this plugin:

    with a thimbthumb using.


    <img border="0" src="<?php echo bloginfo('template_url'); ?>/thimtumb.php?src=<?php resim_cagir(0, "/images/thumbnail.png", "post-img");?>&h=75&w=100&zc=1&q=90" alt="<?php the_title(); ?>" class="postthumbnail" />


    with alone using:

    <img border="0" src="<?php resim_cagir(0, "/images/thumbnail.png", "post-img");?>" alt="<?php the_title(); ?>"/>





    Get Plugin Below

    <?php
    function resim_cagir($index, $default_image='', $img_class='post-image')
    {
    if(!in_the_loop())
    {
    trigger_error("aradiginiz resim su ana bulunamiyor", E_USER_ERROR);
    return 0;
    }

    echo(gpi_get_image($index, $default_image, true, $img_class));
    }

    /*
    Plugin Name: Wordpress resim ekleme
    Plugin URI: http://blog.olcaybal.com/index.php/programlar/wordpresste-sadece-resim-gsterme-get-post-image-for-wordpress
    Description: Wordpress icinde sadace resim gostermek icin pratik bir cozum
    Version: 1.0
    Author: Olcay BAL
    Author URI: http://www.olcaybal.com/

    ******************************************************************************************/
    function gpi_get_image_count()
    {
    global $post;

    if(!in_the_loop())
    {
    trigger_error("gpi_get_image_count can only be used within the post loop", E_USER_ERROR);
    return 0;
    }

    $image_list = gpi_internal_cache_imagelist($post);

    return count($image_list);
    }

    /******************************************************************************************
    resim i�erik olustuam �l�m� ve spesicic deger ama functionu

    ******************************************************************************************/
    function gpi_get_image($index, $default_image='', $as_tag=true, $img_class='post-image')
    {
    global $post;

    if(!in_the_loop())
    {
    trigger_error("gpi_get_image can only be used within the post loop", E_USER_ERROR);
    return 0;
    }

    $info = gpi_internal_get_image_info($post, $index, $default_image);

    if($as_tag)
    {
    //$image = '<img class="' . $img_class . '" src="' . $info['url'] . '" ' . $info['size'] . ' title="' . $info['title'] . '" alt="' . $info['title'] . '" />';

    $image = $info['url'];


    }
    else
    {
    $image = $info;
    }

    return $image;
    }

    /******************************************************************************************
    RESIM url DOYASINI �AGIRACAGIN ALAN

    ******************************************************************************************/




    /*****************************************************************************************
    **
    ** Internal FUNCION ALANI
    **
    *****************************************************************************************/



    // specified image indexleme
    $gpi_image_list_cache = array();



    /******************************************************************************************
    caches imahe indexleme
    ******************************************************************************************/
    function gpi_internal_cache_imagelist($post)
    {
    global $gpi_image_list_cache;

    if (!isset($gpi_image_list_cache[$post->ID]))
    {
    //path yolunda url arama alani
    $match_count = preg_match_all("/<img[^']*?src=\"([^']*?)\"[^']*?>/", $post->post_content, $match_array, PREG_PATTERN_ORDER);

    $gpi_image_list_cache[$post->ID] = $match_array[1];
    }

    return $gpi_image_list_cache[$post->ID];
    }

    /******************************************************************************************

    image listeleme alani

    ******************************************************************************************/
    function gpi_internal_get_image_info($post, $index, $default_image='')
    {
    $image_list = gpi_internal_cache_imagelist($post);

    if ($index < count($image_list))
    {
    $img_url = $image_list[$index];
    }
    else
    {
    $img_url = $default_image;
    }

    // url �zellikleri
    $img_url = urldecode($img_url);

    // server get url alani
    $img_path = ABSPATH . str_replace(get_settings('siteurl'), '', $img_url);

    // image d�ng�leme alani
    if(file_exists($img_path))
    {
    $imagesize = @getimagesize($img_url);
    }
    else
    {
    $imagesize=array();
    }

    // resim alani
    $info = array('title' => $post->post_title, // resim titlesi
    'url' => $img_url, // resim urlsi
    'size' => $imagesize[3], //reism image size (e.g height="60" width="120")
    'width' => $imagesize[0], // sadece genislik
    'height' => $imagesize[1], // sadece yukseklik
    'path' => $img_path, // local path
    'type' => $imagesize[2]); // image ozellik

    return $info;
    }


    ?>

    • 12/30/10 2:28am

      Armand Morin says:

      I have no problem displaying the image. the problem I have is if the post has an image embeded in it, then the display shows TWO IMAGES. One from the thumbnail and one that is embedded into the post.

    • 12/30/10 2:39am

      Rashad Aliyev says:

      Try to use my solution for this. If you still have problem, I should look at it on your site code.

  • avatar
    Last edited:
    12/30/10
    3:50am
    Denzel Chia says:

    Hi,

    If your original posted code works. Please try the following solutions.
    I had created it out of your original code.
    It will not return any image if no first image found.
    I had combined it into a single function.



    <?php
    function first_image() {

    global $post, $posts;

    $post_id = $post->ID;

    $title = get_the_title($post_id);

    $first_img = '';

    ob_start();

    ob_end_clean();

    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);

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

    if(!empty($first_img_src)){

    $image = "<img src='$first_img_src' alt='$title' class='postthumbnail'/>";

    return $image;

    }

    }

    ?>



    How to use


    <?php echo first_image(); ?>

    <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>

    <?php the_content(__('Read More Here...'));?>


    Thanks.
    Denzel

    Previous versions of this answer: 12/30/10 at 2:53am

    • 12/30/10 2:59am

      Armand Morin says:

      Denzel,

      That worked for the first part. Thanks.

      Any ideas on the second part of my question with the duplicate image issue?

    • 12/30/10 3:07am

      Denzel Chia says:

      Sorry,

      I don't understand. Does your original code displays a duplicated image?

      Have you used the solution I provided? And there is still a duplicate image?

      if yes, can you post the whole template code here? There may be duplicated codes else where?

      Please advise.

      Thanks.

    • 12/30/10 3:14am

      Denzel Chia says:

      Hi,

      I see your codes are obtained from here http://www.amitash.com/to-image-automatically-wordpress-post.html

      Actually the code only grabs the first image url from post content, it does not remove it.
      If you use it within the wordpress loop in single.php or page.php
      and there is a <?php the_content(); ?> within the loop.

      This <?php the_content(); ?> will print the content including the first image or any images embedded in it.

      Is this what you are experiencing?

      Thanks.

    • 12/30/10 3:20am

      Armand Morin says:

      The thumbnail code you posted works perfect.

      The issue is that if if the post contains an embedded image, on the main blog page it shows not only the thumbnail, but it also shows the image from that the user inserted. (which is the same image).

      So the questions is, what am I doing wrong or what am I missing?

    • 12/30/10 3:28am

      Denzel Chia says:

      Hi,

      The issue is that if if the post contains an embedded image, on the main blog page it shows not only the thumbnail, but it also shows the image from that the user inserted. (which is the same image).


      In your main blog page template. Is there a function <?php the_content() ?> or <?php the_post_thumbnail(); ?>

      If there is <?php the_post_thumbnail(); ?> just remove it.

      If there is <?php the_content() ?> after or below <?php echo first_image(); ?>
      Then of course it shows two same images. Because <?php echo first_image(); ?> grabs the image from <?php the_content() ?>
      In this case you need a php script to remove or hide it.
      Or simply add a style='display:none' in your html post editor to hide it.

      Thanks.
      Denzel

    • 12/30/10 3:38am

      Denzel Chia says:

      Hi,

      Try the function here to remove the first image from <?php the_content(); ?>
      http://tipsforwordpress.com/wordpress/removing-first-image-from-the_content/

      You can read the post. The writer has the same situation as you.

      Add my solution to the functions from that post and you should achieve what you want.

      Thanks.
      Denzel

    • 12/30/10 3:39am

      Denzel Chia says:

      Forget to mention that you need to put the functions shown here http://tipsforwordpress.com/wordpress/removing-first-image-from-the_content/ in functions.php of your theme.

      Thanks.
      Denzel

    • 12/30/10 3:49am

      Armand Morin says:

      As always... that worked perfectly.

  • avatar
    Last edited:
    12/30/10
    3:39am
    rilwis says:

    Hi Armand,

    The problem of not showing thumbnail if there's no ones) is solved, so I focus on duplication issue.

    A solution for this is using the_content filter, like this (put this in functions.php file):

    add_action('the_content', 'rw_remove_1st_img');
    function rw_remove_1st_img($content) {
    if (preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/iU', $content, $matches)) {
    $content = str_replace($matches[0], '', $content);
    return $content;
    }
    }

This question has expired.



Denzel Chia had additional discourse to offer.



Current status of this question: Completed



Warning: Please do not give out any FTP or ssh credentials to anyone, unless you trust them completely. Giving out login details is dangerous.

If the asker does not get an answer then they have 10 days to request a refund.