WordPress – Simple Social Sharing ShortcodeSaturday, October 31st, 2020

Articles, Quick Tips, Wordpress

Here is a quick tip to add social sharing to your blog articles, custom post types or pages. Most of the time you would probably do this via a plugin, but that adds unnecessary code that slows down the page speed. Yes these plugins may include additional features that you may wish to use but for most people a simple option would be more than adequate.

Copy and paste the code below into your functions.php file:

function wmuk_social_sharing_buttons(){
	global $post;
	$post_id = $post->ID;
	$permalink = get_permalink( $post_id);
	$post_title = get_the_title( $post_id );
	
	if ( has_post_thumbnail($post_id) ) {
		$attachment_id = get_post_thumbnail_id( $post_id );
		$thumbnail_src = wp_get_attachment_image_src($attachment_id, 'large');
		$post_thumbnail = $thumbnail_src[0];
	}else{
		$post_thumbnail = get_bloginfo("template_url").'/images/image_not_found.jpg';
	}
		
	return '
	<h3>Like it? Share it!</h3>	
		<ul class="social_sharing">
			<li><a class="twitter" href="http://twitter.com/home/?status='.$post_title.' - '.$permalink.'" title="Tweet this!"><span class="fa fa-twitter"></span></a></li>
			<li><a class="facebook" href="http://www.facebook.com/sharer.php?u='.$permalink.'&amp;t='.$post_title.'" title="Share on Facebook."><span class="fa fa-facebook"></span></a></li>
			<li><a class="linkedin" href="http://www.linkedin.com/shareArticle?mini=true&amp;title='.$post_title.'&amp;url='.$permalink.'" title="Share on LinkedIn"><span class="fa fa-linkedin"></span></a></li>
		</ul>
	';
}
add_shortcode( 'social_sharing_sc', 'wmuk_social_sharing_buttons' );

As you may be able to tell, we have used an icon font to display the social logos, but you can easily swap these out and use the image icons and adjust the list accordingly with a bit of CSS to appear as you would like to. Grabbing the post featured image is useful, if your sharing link requires an image. For example: Pinterest, we’ve left it here for your convenience and below is the pinterest URL; simply replace the parameters as necessary.

http://pinterest.com/pin/create/button/?url={URI-encoded URL of the page to pin}&media={URI-encoded URL of the image to pin}&description={optional URI-encoded description}

Now thats set up you can open your single.php file and insert the shortcode where you would like the social sharing icons to appear.

echo do_shortcode('[social_sharing_sc]');

An example of this is seen below this article. Go ahead and give it a try 🙂

Like it? Share it!

Tagged with:




Leave a Comment

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