Add Pinterest’s ”Pin It” button to WordPress

This tutorial will show you how to add Pinterest’s Pin-It button to WordPress witout installing a plugin.

With this code you will be able to add the Pin It button to your posts. It will pull the first image from your post to be pinned and link to the post’s URL. The description will be the title of the post.

We have to add two snippets, one function to functions.php and one code in single.php to show the button.

Add the following code in your functions.php:

function pin_it() {
  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 = "/images/default.jpg";
  }
  return $first_img;
}

The function is inspired by WPrecipes.com.

If there is no image in your post the function will pull the default image /images/default.jpg. You can change the default image to whatever you would like.

Place the following code where you want the Pin It button to appear, it should be inside the loop in single.php. If you want to display the button on your homepage you have to add the code in index.php.

<a href="http://pinterest.com/pin/create/button/?url=<?php echo get_permalink(); ?>&media=<?php echo pin_it() ?>&description=<?php the_title(); ?>" class="pin-it-button" count-layout="vertical">Pin It</a>
<script type="text/javascript" src="http://assets.pinterest.com/js/pinit.js"></script>

If you would like to add a horizontal button instead of the vertical button, change count-layout=”vertical” to count-layout=”horizontal”.

The vertical Pin It button looks like this:

Pin It

Gillade du inlägget?

   
       

Kommentera

E-postadressen publiceras inte. Obligatoriska fält är märkta *