Find first image on paginated post for Pinterest

I’ve been looking for days, yet can’t find a good answer. Perhaps the SE crowd can be of assistance. Any help is much appreciated.

I am using a custom-coded pinterest button included on posts that pulls the first image of the post OR the featured image (if exists).

Read More
<span data-icon="0" aria-hidden="true"></span><a href="http://pinterest.com/pin/create/button/?url=<?php echo urlencode(get_permalink($post->ID)); ?>&media=<?php 
if ( (! has_post_thumbnail()) || ($paged != 0) ) { 
echo catch_that_image();
} else { 
// Has featured img
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
echo $image[0]; 
} 
?>&description=<?php the_title(); ?>" class="pin-it-button" count-layout="horizontal">Pin It</a>

Now, the function that fetches the first image of a post looks as follows:

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 = "http://static.purseblog.com/default.jpg";
}
return $first_img;
}

Any idea how to modify the catch_that_image function to take into account the pagination and find the first image on the current page a user browses? I’d like to then send the URL to pinterest for more accurate pinning.

Thanks so much in advance.

Related posts

Leave a Reply

2 comments

  1. Do you mean paginated single posts separated by <!--nextpage-->? If that is the case the function above (catch_that_image()) should work fine. $post->post_content contains the whole post not just the displayed part.

    If you mean a paginated series of different posts the best you will be able to do is get the function to operate on that page of posts, because the other pages are not pulled from the database until they are needed.

  2. Maybe it will be better idea to find the first image by jQuery instead PHP. In this way you can handle the image in visible part of page.

    PS. I didnt write the code because it depends on your HTML.