Need: The ability to control the thumbnail to be used when sharing a post with Facebook.
The Catch: I was trying to share a post with Facebook that had no thumbnail attached to it.
I recently added a Facebook share icon to a clients site, but when I arrived at Facebook after clicking on it, the only thumbnail I was able to select from was an image that appeared sitewide in the sidebar (of course, I could always opt for not displaying an image at all).
The first thing that I needed to do was find a way to specify a thumbnail. To do so, we need to add the following piece of code to the HEAD section of the blog:
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php $szPostContent = get_the_content(); $szSearchPattern = '~<img [^>]* />~'; preg_match_all( $szSearchPattern, $szPostContent, $aPics ); $iNumberOfPics = count($aPics); if ( $iNumberOfPics > 0 ) : ?> <?php $t1 = strpos($aPics, 'src="'); ?> <?php $t2 = strpos($aPics, '"', $t1 + 6); ?> <?php $pixt = substr($aPics, $t1 + 5, $t2 - $t1 - 5); ?> <link rel="image_src" href="<?php echo $pixt; ?>" /> <?php else : ?> <link rel="image_src" href="DEFAULT IMAGE SOURCE" /> <?php endif; ?>
1. I wanted to check the post and see if there was already an image attached to it.
2. For simplicity, I used the first image in the post.
3. If there was an image attached to the post, then I’d want to use it as the thumbnail.
4. I also have a default image set up in the event that no images are included in the post. Make sure to replace “DEFAULT IMAGE SOURCE” with a link to your default image.