Reputation: 33
I have some Pinterest code to show a Pin it button on my wordpress posts but it only grabs the post thumbnail. What I want is to grab the first post content image and only grab the thumbnail if there are no images in the post!??
Have tried tons of examples but nothing works.
<a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink(); ?>&media=<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' ); echo $thumb['0']; ?>&description=<?php the_title(); ?>" class="pin-it-button" count-layout="horizontal">Pin It</a>
Upvotes: 1
Views: 1611
Reputation: 146219
You may try this, just paste following function in your functions.php
function get_first_image()
{
global $post, $posts;
$first_img = '';
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1][0];
if(empty($first_img)) $first_img = false;
return $first_img;
}
Before your Pinterest
code get the image
$thumb=get_first_image();
if(!$thumb)
{
$thumb=wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' );
$thumb=$thumb[0];
}
Then in your Pinterest
link media=<?php echo $thumb; ?>
<a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink(); ?>&media=<?php echo $thumb; ?>&description=<?php the_title(); ?>" class="pin-it-button" count-layout="horizontal">Pin It</a>
Upvotes: 2