There are 2 ways to do this. The first is to create a function that outputs the buttons and then include it in your template. The second is to add a filter to either the_content
or the_excerpt
or both depending on where you want the buttons to show up.
In either case the first thing you need to do is separate out the script calls from the code that renders the buttons and add it to your footer either by hooking into wp_footer
or manually placing the code in footer.php
.
This example uses the Facebook html5 xfbml javascript sdk and the Google async method along with a Linkedin share button and Twitter tweet button.
Add the javascript to the footer
add_action( 'wp_footer', 'prefix_social_media_scripts' );
function prefix_social_media_scripts() {
echo '<script src="http://platform.twitter.com/widgets.js"></script>';
echo '<script src="http://platform.linkedin.com/in.js" type="text/javascript"></script>';
echo '<script>
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, \'script\', \'facebook-jssdk\'));
(function() {
var po = document.createElement(\'script\'); po.type = \'text/javascript\'; po.async = true;
po.src = \'https://apis.google.com/js/plusone.js\';
var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(po, s);
})();
</script>';
}
Function to render the buttons.
function prefix_social_media() {
$post_url = get_permalink();
$title = get_the_title ();
echo '<ul id="share-buttons">';
echo '<li class="facebook"><div class="fb-like" data-href="' . $post_url . '" data-send="false" data-layout="button_count" data-width="66" data-show-faces="false"></div></li>';
echo '<li class="twitter"><a href="http://twitter.com/share" class="twitter-share-button" data-url="' . $post_url . '" data-count="none">Tweet</a></li>';
echo '<li class="google"><div class="g-plusone" data-size="medium" data-href="'.$post_url.'"></div></li>';
echo '<li class="linkedin"><script type="IN/Share" data-url="'. $post_url .'" data-counter="right"></script></li>';
echo '</ul>';
Add filter to display before the_excerpt
.
function prefix_social_media_filters( $content ) {
$buttons = prefix_social_media();
$content = $buttons . $content;
return $content;
}
add_filter( 'the_excerpt', 'prefix_social_media_filters' );
Adding the function to your template.
if (have_posts()) : while (have_posts()) : the_post();
prefix_social_media();
// rest of your loop