A popular request is to build custom “Pin” buttons that overlay images within WordPress blog posts. There are many plugins in the WordPress repo that do that, but I feel it’s better to take care of this with a few lines of code instead of a bloated plugin.
The code below will dynamically create Pinterest Pin It links for each image inside the content area. You’ll want to add a but of CSS to position the link over the image. Also, I recommend wrapping the code below in is_single()
or placing it in single.php
so that it only runs when viewing blog posts.
Lastly, if the image is aligned left/right or as a class of no-pin, the Pinterest button will not be created.
Simple and clean.
<?php | |
/** | |
* Inline javascript | |
* | |
* @since 1.0.0 | |
*/ | |
function ja_pinterest_button() { | |
?> | |
<script type="text/javascript"> | |
jQuery(document).ready(function($) { | |
if ( $( window ).width() > 700 ) { | |
$('.entry-content img').each(function(index, el) { | |
if ( !$(this).hasClass('no-pin') && !$(this).hasClass('alignleft') && !$(this).hasClass('alignright') ) { | |
media = $(this).prop('src'); | |
link = '<a href="http://pinterest.com/pin/create/button/?url=<?php echo urlencode( get_permalink() ); ?>&media=' + media + '&description=<?php echo urlencode( get_the_title() ); ?>" class="pin-it-button">Pin</a>'; | |
$(this).wrap('<div class="pin-image-wrapper"></div>').after(link); | |
} | |
}); | |
} | |
}); | |
</script> | |
<?php | |
} | |
add_action( 'wp_footer', 'ja_pinterest_button' ); |