How to Add Social Sharing to WordPress without a Plugin
This post will show you how to add social sharing to a WordPress theme without a plugin. There are many social sharing plugins for WordPress that I know I could have used. But I do my best to eliminate the use of extra plugins for things that are small. Don’t care about the write-up? Here’s the commented gist that should get you going.
Why not use a plugin?
There are many reasons to do this that would depend on what your or your client’s goals are. In the case of social sharing, I wanted to eliminate including the javascript files for the services. If you look at the documents for how include Facebook, Twitter, or Pinterest sharing buttons on your site, they each state that you should include their code in addition to their corresponding javascript file for best results.
That solution works well if you aren’t concerned with customization or writing additional code to get your buttons to work. But, I did not want to include the javascript files to reduce the number of external calls the website needs to make. If you’ve been developing websites for any amount of time or if you’re a website owner who’s concerned about search engine ranking, page speed has become a significant factor. If you were to analyze your website’s speed – and you’d never done this before – one thing you may notice is that the tool includes an analysis of your third-party requests. Too many requests and your page speed could be impacted. Of course, this would depend on what these third-party resources are responsible for.
Another concern is privacy. Whenever your website loads third-party resources, it’s important to understand what these resources do and what – if any – information they gather from your website and its visitors. You should include this information in your website’s privacy policy, so that users would know which data your website is consuming. If you know what those are and they’re necessary for the function of your website – as in the case of payment processing, etc. – then include them by all means. But for something like a simple social sharing button, I don’t think it’s necessary to include external javascript. When in doubt, leave it out.
How do I do it?
My client’s website is a WooCommerce store. I wanted to include social sharing that could be placed on individual product pages and blog posts or articles. I found a few posts about how to do this, but I’m too lazy to follow them – read as, read through their code to understand what they did and why. So let me walk you through my solution.
First, I went to each service I wanted to set up sharing to and found their instructions for including a button. We’re only sharing to Pinterest, Facebook, and Twitter. If you want to add services that I don’t mention here, you’ll need to do the same thing. What you’re looking for is their sharing link and how it is structured. Copy this into a text file and store it somewhere for future use. Be sure to make a note of the query string parameters they use because you’ll need those for building your markup and such. We’ll be using the add_query_arg
WordPress function to build our link markup.
Most services expect to receive different types of content in the share link request. So don’t take any shortcuts. Here’s the link for sharing to Pinterest, for example.
https://www.pinterest.com/pin/create/button/?url=&media=&description=
The bold text starting with the question mark is the query string. This says to us that to allow website visitors to share our content to Pinterest, we need our button to get the url for the page, the link to the image for that page, and a description of the content.
Another thing you want to do is make sure that your website already has some form of Open Graph support. If you’ve noticed that when you share a link to social media or text message, it populates an image, title and description from only a link? This is Open Graph in action. If you want your links to do the same thing, and you’re using WordPress, installing any good SEO plugin would do that for you.
If you want to roll your own – sans plugin – it’s possible with several lines of code. I won’t cover that here, maybe another time.
After you’ve gathered the links from your providers, it’s time to build your function. You can include this in your functions.php file. If you’re a copy/paster, be sure to provide your own prefix and text domain wherever you see textdomain
in the code.
/**
* Generates social sharing icons and links for posts and products.
*
* For best results, make sure your site already includes OpenGraph support.
* @link https://ogp.me/
*/
function textdomain_social_sharing() {
//Set up the sharing links. We're keeping it basic - Facebook, Twitter, and Pinterest.
$sharing_services = array(
'facebook' => esc_url( 'https://www.facebook.com/sharer/sharer.php' ),
'twitter' => esc_url( 'https://twitter.com/intent/tweet' ),
'pinterest' => esc_url( 'https://www.pinterest.com/pin/create/button/' )
);
//Get the post content to share and set default values.
$post_excerpt = wp_strip_all_tags( get_the_excerpt() );
$share_content = array(
'text' => rawurlencode( esc_html( 'Check out what I found at ' . get_bloginfo( 'name' ) . '.' ) ),
'url' => rawurlencode( get_permalink() ),
'description' => $post_excerpt ? rawurlencode( $post_excerpt ) : rawurlencode( get_the_title() ),
'image-src' => ''
);
// Make sure we're appending to the sharer from single posts and products only, no pages.
// Changing default values where necessary.
if( class_exists( 'WooCommerce' ) && is_product() ) :
/**
* Probably do not need to do this, but WooCommerce template functions uses this same method to grab the main
* product image for single products.
*
* @see woocommerce/templates/single-product/product-image.php
* @see woocommerce/includes/wc-template-functions.php:1552
*/
global $product;
$product_thumbnail_id = $product->get_image_id();
$share_content[ 'image-src' ] = $product_thumbnail_id ? rawurlencode( wp_get_attachment_url( $product_thumbnail_id ) ) : rawurlencode( wc_placeholder_img_src( 'woocommerce_single' ) );
elseif( is_single() ) :
$share_content[ 'image-src' ] = has_post_thumbnail() ? rawurlencode( wp_get_attachment_url( get_post_thumbnail_id() )) : rawurlencode( get_template_directory_uri() . '/path/to/alternate/image.jpg' );
endif;
// Build the markup for the sharing services component. This will hold all buttons.
$share_buttons = '<div class="social-sharing-buttons"><p>Share this:</p>';
// Class arary for social sharing links.
$share_class[] = '';
// Array for query args to append to the url.
$query_args[] = '';
// Build the sharing services link markup to append to the sharing services component.
foreach( $sharing_services as $service_key => $service_url ) :
//Assign CSS classes for each service.
$share_class[$service_key] = $service_key . '-share-btn';
//Initialize query args for each service as empty array.
$query_args[$service_key] = [];
//For each sharing service by key.
switch( $service_key ) :
case 'facebook':
//Assign it's specific query arguments.
$query_args[$service_key] = [
'u' => $share_content['url'],
];
//Append the sharing service button to the markup.
$share_buttons .= '<a href="' . esc_url( add_query_arg( $query_args[$service_key], $service_url ) ) . '" class="' . $share_class[$service_key] . '" aria-label="' . esc_attr__( 'Share to Facebook', 'textdomain' ) . '" rel="nofollow noopener" target="_blank"></a>';
break;
case 'twitter':
$query_args[$service_key] = [
'text' => $share_content['text'],
'url' => $share_content['url'],
];
$share_buttons .= '<a href="' . esc_url( add_query_arg( $query_args[$service_key], $service_url ) ) . '" class="' . $share_class[$service_key] . '" aria-label="' . esc_attr__( 'Share to Twitter', 'textdomain' ) . '" rel="nofollow noopener" target="_blank"></a>';
break;
case 'pinterest':
$query_args[$service_key] = [
'url' => $share_content['url'],
'media' => $share_content['image-src'],
'description' => $share_content['description'],
];
$share_buttons .= '<a href="' . esc_url( add_query_arg( $query_args[$service_key], $service_url ) ) . '" class="' . $share_class[$service_key] . '" aria-label="' . esc_attr__( 'Pin to Pinterest', 'textdomain' ) . '" rel="nofollow noopener" target="_blank"></a>';
break;
endswitch;
endforeach;
//Close the share buttons markup.
$share_buttons .= '</div>';
//Return the share buttons for display.
echo $share_buttons;
}
Now that you’ve got your markup together, it’s time to apply some styles. Even though my theme includes FontAwesome, I chose to use the ::before
CSS pseudo-element to apply the social icons. I didn’t really feel like adding the <i class="">
markup that you could use with FontAwesome. I felt that that links were long enough and adding the icons in CSS seemed simpler. But, you do it however you want to do it.
Adding the Social Sharing to the Site
Now that we’re done, we want to add this to the site. For individual posts, you simply open your single content template and call the function textdomain_social_sharing();
wherever you want the sharing links to appear. To add social sharing to every WooCommerce single product page, use the action hook do_action( 'woocommerce_share' );
. So in your WooCommerce compatibility file, or functions.php, you’d call it like add_action( 'woocommerce_share', 'textdomain_social_sharing' );
. This hook is provided in the woocommerce/templates/single-product/share.php
file. If you have not overridden content-single-product.php
, this will append the content of the share template file to the end of the woocommerce_single_product_summary
action hook. That would place it beneath the product meta where the SKU and categories show up.
I hope this helped. Happy Coding. 🙂
Was this helpful? Have a question? Notice an error? Leave me a comment below.