Custom Code to Add a Social Media Share Button in WordPress

Marek K Feb 5, 2025 Social Media Integration
How do I add a button to my blog so that people can share my posts on social media?
What code snippet can I implement in my WordPress theme to add social media share buttons to my posts?
Andy answered Feb 5, 2025

Custom Social Share Buttons Solution

Custom Code Implementation

Add this function to your theme's functions.php file to create social sharing buttons that will appear below your post content:

function add_social_share_buttons($content) {
    // Only show on single posts
    if(is_single()) {
        // Get current page URL
        $url = urlencode(get_permalink());
        // Get current page title
        $title = urlencode(get_the_title());
        
        // Share button links
        $facebook_url = 'https://www.facebook.com/sharer/sharer.php?u=' . $url;
        $twitter_url = 'https://twitter.com/intent/tweet?text=' . $title . '&url=' . $url;
        $linkedin_url = 'https://www.linkedin.com/shareArticle?mini=true&url=' . $url . '&title=' . $title;
        
        // Build sharing buttons HTML
        $buttons = '<div class="social-share-buttons">';
        $buttons .= '<a href="' . $facebook_url . '" target="_blank" class="share-button facebook">Share on Facebook</a>';
        $buttons .= '<a href="' . $twitter_url . '" target="_blank" class="share-button twitter">Share on Twitter</a>';
        $buttons .= '<a href="' . $linkedin_url . '" target="_blank" class="share-button linkedin">Share on LinkedIn</a>';
        $buttons .= '</div>';
        
        return $content . $buttons;
    }
    return $content;
}
add_filter('the_content', 'add_social_share_buttons');

Add this CSS to your theme's style.css file to style the buttons:

.social-share-buttons {
    margin: 20px 0;
    padding: 20px 0;
    border-top: 1px solid #ddd;
}

.share-button {
    display: inline-block;
    padding: 10px 20px;
    margin-right: 10px;
    color: #fff;
    text-decoration: none;
    border-radius: 4px;
}

.facebook {
    background: #3b5998;
}

.twitter {
    background: #55acee;
}

.linkedin {
    background: #0077b5;
}

.share-button:hover {
    opacity: 0.8;
}

Plugin Alternatives

If you prefer using a plugin, here are reliable options:

  1. Social Warfare - Professional-looking share buttons with share counts
  2. Sassy Social Share - Lightweight plugin with multiple styling options
  3. AddToAny Share Buttons - Simple and clean sharing buttons

Important Notes

  • The custom code solution uses the the_content filter hook, which works with most themes
  • The buttons will appear below post content on single post pages only
  • The code includes sharing for Facebook, Twitter, and LinkedIn, but you can add more platforms by following the same pattern
  • Social platforms may change their sharing URLs over time, so keep the code updated
  • Test the buttons on your site as some themes might require CSS adjustments