Add ‘Pin it’ to WordPress Theme

Pinterest has a ‘Pin It’ button available for websites in the ‘Goodies‘ section now. It’s much like the Twitter and Facebook buttons you see EVERYwhere. I added a bit so you can use it in your WordPress theme.

With the following code this button can go on your index, single or archive pages – anywhere the WordPress loop appears. It will automatically pull the first image from the post to be pinned and link to the post’s permalink. The title of the post along with the website url will appear in the description field but can be edited before it’s posted.

Place this code in your template where you want the ‘Pin It’ button to appear – it should be inside The Loop.

<a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink() ?>&media=<?php echo pinterest_image() ?>&description=<?php the_title(); ?> on <?php bloginfo('url'); ?>" class="pin-it-button" count-layout="horizontal">Pin It</a>

Place this script in your footer.php file, just before the closing tag.

<script type="text/javascript" src="http://assets.pinterest.com/js/pinit.js"></script>

Put the following code in your functions.php file.

function pinterest_image() {
  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;
}

You can change /images/default.jpg to whatever you’d like. This image will be pinned if there’s not an image in the post.

Be really careful in your functions.php file, it’s a little touchier than what you might be used to. The first thing I ever broke in one was putting a space after the closing ?> – it’ll break your whole site! Always back up your files before you start changing things.

Easy as that, happy pinning!

P.S. Before you ask a question about your WordPress theme please do a quick google or codex search – If you still can’t figure it out ask away and I’ll try my best to help when I can!

.

UPDATE!

Due to Pinterest’s huge popularity now, there are tons of plugins available that will do this for you. I just did a quick search and this one looks good. WP Beginner also shows a different method that doesn’t involve the function file.

Leave a Reply

Your email address will not be published. Required fields are marked *


× five = 25

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>