troubles with getting pinterest pin-it button working on wordpress single posts

When updating themarshmallowstudio.com’s blog, I added a bunch of those annoying, but effective and sometimes useful social ‘like’ buttons so that people could share and ‘like’ or ‘pin’ the posts (mostly because of our demographic), but that’s a whole ‘nother story.

The problem lies when working with the pinterest pin-it button that tracks the number of pins from each post. I am sure there are a wealth of great wordpress plugins that handle this well, but I am getting really tired of looking for a plugin to solve a seemingly simple problem that I could figure out in about 10min. rather than try to research and make sure the plugin isn’t doing anything malicious to the blog or opening security holes (sorry wp plugin developers, but no, I don’t trust you as much as I trust myself).

Since pinterest isn’t really meant to pin blog posts, especially ones with lots of images in the body content, I had to come up with an automated way to give the tracker the data it needed based off the author’s input and not have to manually update the url or send it through some wacky api pre-processor.

My solution was (kinda) simple and I will share the code below.

the ‘pin-it’ button needs (3) inputs in the URL to work.
-The URL of the page for linking
-The URL of the image to use as a thumbnail
-A description for the pin (optional, but definitely recommended)

The permalink URL is a no brainer and I decided to use the post title as the description, but getting the permalink image URL provided a little more challenging because of multiple images, which one do I want to use for the thumbnail? For this, I enabled the post thumbnail feature in WP by adding the following tag to my functions.php file

add_theme_support('post-thumbnails');

This enables an author of a post to select a “Featured Image” when writing the post.

Finally, I created a small script to strip out the permalink URL for the image selected as the Featured Image and urlencode it to send to the pin-it button script. The final output is below for reference

//separate script
<?php
  $pinURL = urlencode(get_permalink());
  $pinThumbAr = explode("src="", get_the_post_thumbnail());
  $pinThumb = explode(".jpg",$pinThumbAr[1]);
  $pinThumbUrl = urlencode($pinThumb[0].".jpg");
?>
//a tag
<span class="pin-home-btn"><a href="http://pinterest.com/pin/create/button/?url=<?php echo $pinURL; ?>&media=<?php echo $pinThumbUrl; ?>&description=<?php echo urlencode(the_title()); ?>" class="pin-it-button" count-layout="horizontal"><img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" /></a></span>

quick and dirty, but it works and doesn’t require a plugin to be updated and worried about security.