Add Share-to-Social Links to WordPress Posts

Add share to social links to WordPress posts

Learn how to add share-to-social network links to any WordPress content without installing a plugin. We’ll use some simple PHP to hook the content and inject the links & icons. The tutorial is easy to customise and you can add your own networks too.

importantMake sure you’re using a custom child theme so you can edit “functions.php”.

Sharing links

Define the problem

As with any project, the first thing we need to do is define the objective. In this case, we want to add share-to-social buttons to the end of posts, pages, products or any other content we want…

  1. Choose which post types have the share-to-social links. Default should be “posts”.
  2. Start with Facebook, Twitter & LinkedIn and make it easy to add more networks.
  3. Keep the HTML super simple so there are no problems with mobile browsers.
  4. Make sure the links are OK for SEO by using nofollow and/or noopener properly.

The final output will be a div element with some child links in it, like this:

<div class="share-to-socials">
	<div class="share-to-facebook">
		<a href="https://www.facebook.com/share.php?u=https://example.com/your-post">
			<svg>...</svg>
		</a>
	</div>
	<div class="share-to-twitter">
		<a href="https://twitter.com/share?url=%s">
			<svg>...</svg>
		</a>
	</div>
	<!--
	   More networks in here...
	-->
</div>

Every social media platform has a URL schema that allows quick sharing of external content to their network, although it can take some effort to find it in their documentation.

Scaffold the code

Start by going into your custom child theme and creating a file called “wpt-share-to-socials.php”, then paste the following into it:

<?php

/**
 * Headwall WP Tutorials Share to Socials : WPTSTS
 *
 * https://wp-tutorials.tech/refine-wordpress/add-share-to-social-links-to-wordpress-posts/
 *
 */
defined('WPINC') || die();

/**
 * The post types that will have the share-to-social links at the end. This
 * constant can be null, false, a string with a single post type, or an array of
 * post types.
 *
 * const WPTSTS_POST_TYPES_TO_SHARE = null;     // Disabled the social links completely
 * const WPTSTS_POST_TYPES_TO_SHARE = 'post';   // Only show on single posts
 * const WPTSTS_POST_TYPES_TO_SHARE = array('post', 'page', 'product');
 *
 */
const WPTSTS_POST_TYPES_TO_SHARE = 'post';

const WPTSTS_OPEN_IN_NEW_TAB = true;

/**
 * The list of networks we want to share to. Each of these needs a corresponding
 * filter-handler to create the link and icon HTML.
 *
 * If you add support for sharing to Yandex, add "yandex" to the WPTSTS_NETWORKS
 * array and create a filter handler called "get_share_to_yandex". Look at how
 * we implement the "facebook" network and use that as your template.
 *
 */
const WPTSTS_NETWORKS = array('facebook', 'twitter', 'linkedin');

/**
 * Simple SVGs to get started. You could swap these out for things like
 * '<i class="fab fa-facebook-square"></i>' if your site has Font Awesome
 * installed.
 */
const WPTSTS_FACEBOOK_ICON = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!-- Font Awesome Pro 5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) --><path d="M400 32H48A48 48 0 0 0 0 80v352a48 48 0 0 0 48 48h137.25V327.69h-63V256h63v-54.64c0-62.15 37-96.48 93.67-96.48 27.14 0 55.52 4.84 55.52 4.84v61h-31.27c-30.81 0-40.42 19.12-40.42 38.73V256h68.78l-11 71.69h-57.78V480H400a48 48 0 0 0 48-48V80a48 48 0 0 0-48-48z"/></svg>';
const WPTSTS_TWITTER_ICON = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!-- Font Awesome Pro 5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) --><path d="M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zm-48.9 158.8c.2 2.8.2 5.7.2 8.5 0 86.7-66 186.6-186.6 186.6-37.2 0-71.7-10.8-100.7-29.4 5.3.6 10.4.8 15.8.8 30.7 0 58.9-10.4 81.4-28-28.8-.6-53-19.5-61.3-45.5 10.1 1.5 19.2 1.5 29.6-1.2-30-6.1-52.5-32.5-52.5-64.4v-.8c8.7 4.9 18.9 7.9 29.6 8.3a65.447 65.447 0 0 1-29.2-54.6c0-12.2 3.2-23.4 8.9-33.1 32.3 39.8 80.8 65.8 135.2 68.6-9.3-44.5 24-80.6 64-80.6 18.9 0 35.9 7.9 47.9 20.7 14.8-2.8 29-8.3 41.6-15.8-4.9 15.2-15.2 28-28.8 36.1 13.2-1.4 26-5.1 37.8-10.2-8.9 13.1-20.1 24.7-32.9 34z"/></svg>';
const WPTSTS_LINKEDIN_ICON = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!-- Font Awesome Pro 5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) --><path d="M416 32H31.9C14.3 32 0 46.5 0 64.3v383.4C0 465.5 14.3 480 31.9 480H416c17.6 0 32-14.5 32-32.3V64.3c0-17.8-14.4-32.3-32-32.3zM135.4 416H69V202.2h66.5V416zm-33.2-243c-21.3 0-38.5-17.3-38.5-38.5S80.9 96 102.2 96c21.2 0 38.5 17.3 38.5 38.5 0 21.3-17.2 38.5-38.5 38.5zm282.1 243h-66.4V312c0-24.8-.5-56.7-34.5-56.7-34.6 0-39.9 27-39.9 54.9V416h-66.4V202.2h63.7v29.2h.9c8.9-16.8 30.6-34.5 62.9-34.5 67.2 0 79.7 44.3 79.7 101.9V416z"/></svg>';

/**
 * Enqueue our styles.
 */
function wptsts_enqueue_scripts_and_styles() {
	if (wptsts_are_share_links_required()) {
		$theme_version = wp_get_theme()->get('Version');
		$base_uri = get_stylesheet_directory_uri();

		wp_enqueue_style(
			'wptsts',
			$base_uri . 'https://cdn.wp-tutorials.tech/wpt-share-to-socials.css',
			null, // No style dependencies
			$theme_version
		);
	}
}
add_action('wp_enqueue_scripts', 'wptsts_enqueue_scripts_and_styles');

/**
 * If you want to dynamically change which social network sharing links are
 * visible, based on the content, you can use the "wptsts_networks" filter to
 * return a different array of networks.
 */
function wptsts_share_to_networks() {
	return (array) apply_filters('wptsts_networks', WPTSTS_NETWORKS);
}

/**
 * This lets us control which content should have the share-to-social links
 * enabled. This function is only triggered on singular content - not on archive
 * pages.
 */
function wptsts_are_share_links_required() {
	$are_required = false;

	if (is_admin() || wp_doing_ajax()) {
		// ...
	} else {
		$current_post_type = get_post_type();

		if (empty(WPTSTS_POST_TYPES_TO_SHARE)) {
			// No post types are specified, so social sharing is effectivel
			// disabled.
		} elseif (is_string(WPTSTS_POST_TYPES_TO_SHARE)) {
			$are_required = ($current_post_type == WPTSTS_POST_TYPES_TO_SHARE);
		} elseif (is_array(WPTSTS_POST_TYPES_TO_SHARE)) {
			$are_required = in_array($current_post_type, WPTSTS_POST_TYPES_TO_SHARE);
		} else {
			// WPTSTS_POST_TYPES_TO_SHARE is an unsupported type.
			error_log(__FUNCTION__ . ' : WPTSTS_POST_TYPES_TO_SHARE should be either null, false, a string or an array of strings');
		}
	}

	return $are_required;
}

/**
 * A utility function to get the current content's URL without any query args
 */
function wptsts_get_current_request_url() {
	global $wp;
	return home_url(add_query_arg(array(), $wp->request));
}

/**
 * Our core function that loops over the requires social networks and builds
 * the HTML.
 */
function wptsts_maybe_inject_share_links($content) {
	// TODO: Our core code will go in here...
	// ...

	return $content;
}
add_filter('the_content', 'wptsts_maybe_inject_share_links', 10, 1);

/**
 * Facebook filter handler.
 */
function wptsts_get_share_to_facebook($html, $share_url, $link_props) {
	$html .= sprintf(
		'<a href="https://www.facebook.com/share.php?u=%s" %s>%s</a>',
		esc_attr($share_url),
		$link_props,
		WPTSTS_FACEBOOK_ICON
	);

	return $html;
}
add_action('get_share_to_facebook', 'wptsts_get_share_to_facebook', 10, 3);

Next, create a file called “wpt-share-to-socials.css” and add the following to it:

/**
 * Headwall WP Tutorials Share to Socials : WPTSTS
 *
 * https://wp-tutorials.tech/refine-wordpress/add-share-to-social-links-to-wordpress-posts/
 *
 */
.share-to-socials,
.share-to-socials a,
.share-to-socials a svg {
	margin:  0;
	padding:  0;
	line-height: 1;
}

.share-to-socials > div {
	display:  inline-block;
}

.share-to-socials a > * {
	width:  2em;
}

.share-to-socials > div:not( :last-child ) {
	margin-right: 1em;
}

.share-to-socials .share-to-facebook i,
.share-to-socials .share-to-facebook svg path {
	fill:  #4267B2;
}

.share-to-socials .share-to-twitter i,
.share-to-socials .share-to-twitter svg path {
	fill:  #1DA1F2;
}

.share-to-socials .share-to-linkedin i,
.share-to-socials .share-to-linkedin svg path {
	fill:  #0072b1;
}

Finally, open your child theme’s functions.php file and add the following couple of lines:

// WP Tutorials : Social share links
require_once dirname(__FILE__) . '/wpt-share-to-socials.php';

How the code works

The PHP code contains the following standard components:

  • At the top, we block direct access to the PHP file by verifying that WPINC has been defined by WordPress core.
  • We define the constants that control how our project will work.
  • wptsts_are_share_links_required() needs to return true on any singular (not archive) content that needs the social sharing links.
  • Hook the wp_enqueue_scripts action to add a reference to our CSS file in the header. We only include our CSS on content that needs it, by checking the output of wptsts_are_share_links_required().
  • wptsts_maybe_inject_share_links() is our core function that does the actual work. It hooks the the_content filter to modify the WordPress post content that gets rendered to the page. If wptsts_are_share_links_required() returns true, we just take the HTML that the_content has already created, and we append our HTML to the end of it.
  • Each social network is supported by a filter handler like “get_share_to_facebook” or “get_share_to_twitter”. These handlers should return <a href="...">icon in here</a>. The icon can be whatever you want – we’re using inline SVGs, but you could use things like <i class="fab fa-facebook-square"></i> if Font Awesome is available on your site.

Featured plugin

UK Gift Aid for WooCommerce
Add a UK Gift Aid consent checkbox to any WooCommerce checkout. Enable site-wide or for specific products. Accept donations from anywhere on your site, including at the checkout.
UK Gift Aid & Donations for WooCommerce

The Core function

Go back into wpt-share-to-socials.php and replace the contents of wptsts_maybe_inject_share_links() with the following:

function wptsts_maybe_inject_share_links($content) {
	if (is_admin() || wp_doing_ajax() || !in_the_loop() || !is_main_query()) {
		// ...
	} elseif (!wptsts_are_share_links_required()) {
		// Socials are not enabled here.
	} elseif (empty($networks = wptsts_share_to_networks())) {
		// No networks are specified.
	} elseif (empty($share_url = wptsts_get_current_request_url())) {
		// The current/share URL is empty. We should never end up in there.
		error_log(__FUNCTION__ . ' The current/share URL is empty. Weird.');
	} else {
		$sharing_html = '';

		foreach ($networks as $network) {
			$link_props = sprintf(
				'title="%s %s"',
				esc_attr__('Share this post to', 'wp-tutorials'),
				esc_attr($network)
			);

			if (WPTSTS_OPEN_IN_NEW_TAB) {
				$link_props .= ' rel="nofollow noopener" target="_blank"';
			} else {
				$link_props .= ' rel="nofollow noreferrer"';
			}

			$filter_name = 'get_share_to_' . $network;
			$share_to_network_html = (string) apply_filters($filter_name, '', $share_url, $link_props);

			if (!empty($share_to_network_html)) {
				$sharing_html .= sprintf(
					'<div class="share-to-%s">%s</div>',
					esc_attr($network),
					$share_to_network_html
				);
			}
		}

		if (!empty($sharing_html)) {
			$content .= '<div class="share-to-socials">';
			$content .= $sharing_html;
			$content .= '</div>'; // .share-to-socials
		}
	}

	return $content;
}

The structure should be easy to follow, and it breaks down like this:

  • Fail if the execution conditions aren’t right
  • Log an error if the input parameters are invalid
  • Create an empty string to hold our HTML, $sharing_html
  • For each social network…
    • Get the HTML for the share-to-social link
    • If the HTML is not empty, then…
      • Append the HTML to $sharing_html
  • If $sharing_html is not empty, then…
    • Append $sharing_html to the post’s content HTML
  • Return the post’s content HTML (which may or may not be modified)

Make sure everything is saved, then reload a single post on your site. You should see the Facebook social network icon at the end of your content 👍.

Adding more social networks

We’ve got “facebook”, “twitter” and “linkedin” specified in WPTSTS_NETWORKS but we’ve only got a filter-handler for Facebook. So let’s add filter handlers for the other two networks now. Go to the end of wpt-share-to-socials.php and append the following:

/**
 * Twitter filter handler.
 */
function wptsts_get_share_to_twitter($html, $share_url, $link_props) {
	$html .= sprintf(
		'<a href="https://twitter.com/share?text=%s&url=%s" %s>%s</a>',
		esc_attr(get_the_title()),
		esc_attr($share_url),
		$link_props,
		WPTSTS_TWITTER_ICON
	);

	return $html;
}
add_action('get_share_to_twitter', 'wptsts_get_share_to_twitter', 10, 3);

/**
 * LinkedIn filter handler.
 */
function wptsts_get_share_to_linkedin($html, $share_url, $link_props) {
	$html .= sprintf(
		'<a href="https://www.linkedin.com/sharing/share-offsite/?url=%s" %s>%s</a>',
		esc_attr($share_url),
		$link_props,
		WPTSTS_LINKEDIN_ICON
	);

	return $html;
}
add_action('get_share_to_linkedin', 'wptsts_get_share_to_linkedin', 10, 3);

There’s no rocket-science in there – each function just returns a simple chunk of HTML that allows sharing to that network.

To add a completely new network, add the network’s name to the WPTSTS_NETWORKS array and then add a filter-handler for it. Use the Facebook network as an example.

That’s it. Happy socialising 😎 👍

Like This Tutorial?

Let us know

WordPress plugins for developers

1 thought on “Add Share-to-Social Links to WordPress Posts”

  1. Hey, I felt compelled to reach out and let you know how much I appreciated reading your website. Your ideas are genuinely amazing and have inspired me with a different outlook. I will be adding it to my own bookmarks and look forward to checking out your future posts. Thank you for putting in the time and keep up the fantastic job!

    Reply

Leave a comment