Add Facebook and Twitter buttons in WordPress

If you want to increase engagement on your WordPress posts, a great option is to add Facebook’s “Like” button and Twitter’s “Share” button. In this article, I’ll show you how to do it easily without additional plugins.

We’ll add the buttons below the title of each post. To do this, we’ll edit the functions.phpfile and the post template file.

 

Add the code to functions.php

Edit your theme’s functions.phpfile and add the following function to generate the buttons:

<?php
function addSocialButtons( $content ) {
    if ( is_single() ) {
        $postUrl   = get_permalink();
        $postTitle = get_the_title();

        $facebookBtn  = '<div class="socialButtons">';
        $facebookBtn .= '<iframe src="https://www.facebook.com/plugins/like.php?href=' . urlencode( $postUrl ) . '&width=100&layout=button&action=like&size=small&share=false&height=21" width="100" height="21" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allow="autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share"></iframe>';

        $twitterBtn = '<a href="https://twitter.com/share?url=' . urlencode( $postUrl ) . '&text=' . urlencode( $postTitle ) . '" target="_blank" class="twitterShareButton">Share on Twitter</a>';

        $facebookBtn .= $twitterBtn . '</div>';

        return $facebookBtn . $content;
    }

    return $content;
}
add_filter( 'the_content', 'addSocialButtons' );

 

Add optional CSS styles

To make the buttons look better, add these styles to your theme’s style.cssfile:

.socialButtons {
    margin-bottom: 15px;
    display: flex;
    gap: 10px;
    align-items: center;
}
.twitterShareButton {
    display: inline-block;
    background-color: #1DA1F2;
    color: #fff;
    padding: 5px 10px;
    border-radius: 5px;
    text-decoration: none;
    font-size: 14px;
}
.twitterShareButton:hover {
    background-color: #0d8ddb;
}

 

With this code, the buttons will automatically appear below the title of each post in WordPress. That’s it!

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top