How to Add A Pinterest Button on Your Website Images When Hovered

With all the success that Pinterest is getting for its users, I was looking for a way to incorporate a pin it button to some images on one of our sister web pages. I found an article posted by Toan Nguyen Minh of uxde.net where he had an option to add one, but I was looking for something more specific.  I  searched on the internet for something similar to what I had in mind.  

When I found it here, I shared it with Toan.  I did not expect anything from it, more than to share my frustration.  A few hours later I received an email saying that there was a response to my comment on Toan’s page.  When I checked it out, I was amazed to have found that he had answered my question not only with any answer but the exact code I was looking for.

I learn a lot by searching for countless hours online on how to do things for my websites.  He definantly cut my time by 1/4.  Anyway here is the code to implement a pinterest button on a image when hovered over. No plugin required.

 

Step 1: Functions Your WordPress Theme

Add the following code to your functions.php file on your current wordpress theme.

function insert_pinterest($content) {
	global $post;
	$posturl = urlencode(get_permalink()); //Get the post URL
	$pindiv = '<div class="pinterest-button">';
	$pinurl = '<a href="http://pinterest.com/pin/create/button/?url='.$posturl.'&media=';
	$pindescription = '&description='.urlencode(get_the_title());
	$pinfinish = '" class="pin-it"></a>';
	$pinend = '</div>';
	$pattern = '/<img(.*?)src="(.*?).(bmp|gif|jpeg|jpg|png)"(.*?) \/>/i';
  	$replacement = $pindiv.$pinurl.'$2.$3'.$pindescription.$pinfinish.'<img$1src="$2.$3" $4 />'.$pinend;
	$content = preg_replace( $pattern, $replacement, $content );
	//Fix the link problem
	$newpattern = '/<a(.*?)><div class="pinterest-button"><a(.*?)><\/a><img(.*?)\/><\/div><\/a>/i';
	$replacement = '<div class="pinterest-button"><a$2></a><a$1><img$3\/></a></div>';
	$content = preg_replace( $newpattern, $replacement, $content );
	return $content;
}
add_filter( 'the_content', 'insert_pinterest' );

Step 2: CSS Makeup

.pinterest-button {
position: relative;
}
.pin-it {
display:block;
width:105px;
height:105px;
background:url('images/pinterest-button.png');
z-index:10;
margin:0;
position:absolute;
bottom: 20px;
right: 15px;
float:left;
}
.pinterest-button .pin-it {
display:none;
}
.pinterest-button:hover .pin-it {
display:block;
}

Live Demo

Credit : Toan w/ http://www.uxde.net/

Thanks again! Awesome work!

This entry was posted in Web Design, Wordpress. Bookmark the permalink.

Comments are closed.