Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Grab First Post Image and Ignore Embeded Images WordPress

  • SOLVED

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.

Answers (4)

2010-12-30

Denzel Chia answers:

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


Armand Morin comments:

Denzel,

That worked for the first part. Thanks.

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


Denzel Chia comments:

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.


Denzel Chia comments:

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.


Armand Morin comments:

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?


Denzel Chia comments:

Hi,

<blockquote>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).</blockquote>

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


Denzel Chia comments:

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


Denzel Chia comments:

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


Armand Morin comments:

As always... that worked perfectly.

2010-12-30

Pau answers:

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


Armand Morin comments:

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.


Pau comments:

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;

}


2010-12-30

Rashad Aliyev answers:

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


?>


Armand Morin comments:

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.


Rashad Aliyev comments:

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

2010-12-30

rilwis answers:

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