WordPress snippets to work with social networks

Social networks are very important on the internet and can bring tons of traffic to your website. Today, I have compiled my favorites WordPress code snippets to work with social networks as such as Facebook, Twitter, Pinterest, Google+, and more.

Automatically add Open Graph to your posts

Open Graph is a protocol created by facebook which allow you to make your content easily recognizable by social networks.

To automatically add Open Graph metadata to your posts, let’s start by pasting the following code snippet into your functions.php file.

function wptuts_opengraph_for_posts() {
    if ( is_singular() ) {
        global $post;
        setup_postdata( $post );
        $output = '<meta property="og:type" content="article" />' . "\n";
        $output .= '<meta property="og:title" content="' . esc_attr( get_the_title() ) . '" />' . "\n";
        $output .= '<meta property="og:url" content="' . get_permalink() . '" />' . "\n";
        $output .= '<meta property="og:description" content="' . esc_attr( get_the_excerpt() ) . '" />' . "\n";
        if ( has_post_thumbnail() ) {
            $imgsrc = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
            $output .= '<meta property="og:image" content="' . $imgsrc[0] . '" />' . "\n";
        echo $output;
add_action( 'wp_head', 'wptuts_opengraph_for_posts' );

Then, open your header.php and replace the <html> tag by this:

<html <?php language_attributes(); ?> prefix="og: http://ogp.me/ns#">

Source: http://wp.tutsplus.com/articles/general/5-essential-tips…

Create a Pinterest “pin it” button for your blog

Pinterest is a website where people can create and share bookmarks of interesting stuff they find among the web. Like Facebook or Twitter, a Pinterest button can be added to your posts in order to make it easy for people to add your content to the network.

The first thing to do is to paste the following snippet where you’d like the “Pin It” button to be displayed. Note that this code must be inserted within the loop.

<a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink(); ?>&media=<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' ); echo $thumb['0']; ?>&description=<?php the_title(); ?>" class="pin-it-button" count-layout="horizontal">Pin It</a>

Once done, open your footer.php file and add the Pinterest JavaScript code:

<script type="text/javascript" src="http://assets.pinterest.com/js/pinit.js"></script>

Source: http://www.marketingtechblog.com/wordpress-pinterest-button/

Display your latest tweet on your blog without using a plugin

Many plugins are available if you’re looking for a way to display your latest tweet on your blog. But you don’t really need to install a plugin for that.

Simply paste the following code anywhere in your theme files, where you want the tweets to be displayed. Don’t forget to update the code with your username on line 3. Max items to display can be defined on line 4.

include_once(ABSPATH . WPINC . '/feed.php');
$rss = fetch_feed('https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=catswhocode');
$maxitems = $rss->get_item_quantity(3);
$rss_items = $rss->get_items(0, $maxitems);

<?php if ($maxitems == 0) echo '<li>No items.</li>';
// Loop through each feed item and display each item as a hyperlink.
foreach ( $rss_items as $item ) : ?>
<a href='<?php echo $item->get_permalink(); ?>'>
<?php echo $item->get_title(); ?>
<?php endforeach; ?>

Source: http://wp.smashingmagazine.com/2012/01/19/facebook-twitter-google-wordpress/

Add a Google+ button to your posts

Google+ is a social network from Google, and it’s becoming more popular day by day. To add a google+ button to your posts, simply open your functions.php file and paste the following code in it:

add_filter('the_content', 'wpr_google_plusone');
function wpr_google_plusone($content) {
	$content = $content.'<div class="plusone"><g:plusone size="tall" href="'.get_permalink().'"></g:plusone></div>';
	return $content;
add_action ('wp_enqueue_scripts','wpr_google_plusone_script');
function wpr_google_plusone_script() {
	wp_enqueue_script('google-plusone', 'https://apis.google.com/js/plusone.js', array(), null);

Source: http://spyrestudios.com/17-time-saving-code-snippets-for-wordpress-developers/

Display your lastest Google+ update

If you’re a Google+ user, you might want to display your latest Google+ update. To do so, paste the code below where you want to display your latest Google+ update. Just don’t forget to put your Google+ ID on line 3.

	$googleplus = fetch_feed("http://plusfeed.appspot.com/103329092193061943712"); // Replace 103329092193061943712 by your own ID
	echo '<a href="';
	echo $googleplus->items[0]['link']; echo '">';
	echo $googleplus->items[0]['summary'];
	echo '';

Source: http://www.geekeries.fr/snippet/afficher-mise-a-jour-google-plus

Automatically add Twitter and Facebook buttons to your posts

Facebook and Twitter are the two most popular social networks, and they can provide lots of traffic to your website. In order to make it easy for people to share your posts on Twitter and Facebook, paste this code into your functions.php file and save it. It will display both Facebook and Twitter buttons, like those you can see at the bottom of this post.

function share_this($content){
    if(!is_feed() && !is_home()) {
        $content .= '<div class="share-this">
                    <a href="http://twitter.com/share"
                    <script type="text/javascript"
                    <div class="facebook-share-button">
scrolling="no" frameborder="0" style="border:none;
overflow:hidden; width:200px; height:21px;"
    return $content;
add_action('the_content', 'share_this');

Source: http://www.wprecipes.com/automatically-add-twitter-and-facebook-buttons-to-your-posts

Display your favorite tweets with WordPress

Paste this code where you want your favorite tweets to be displayed. Don’t forget to update your favorite feed url on line 3.

    include_once(ABSPATH . WPINC . '/feed.php');
    $rss = fetch_feed('http://twitter.com/favorites/793830.rss');
    $maxitems = $rss->get_item_quantity(3); 
    $rss_items = $rss->get_items(0, $maxitems);

    <?php if ($maxitems == 0) echo '<li>No items.</li>';
    // Loop through each feed item and display each item as a hyperlink.
    foreach ( $rss_items as $item ) : ?>
        <a href='<?php echo $item->get_permalink(); ?>'>
            <?php echo $item->get_title(); ?>
    <?php endforeach; ?>

Source: http://css-tricks.com/snippets/wordpress/display-rss-in-wordpress/

Display how many times a post has been shared on twitter

If you want to display how many times a post has been shared on Twitter, simply paste the function below into your functions.php file:

function readTwitterShares($url) {
 $s = file_get_contents("http://urls.api.twitter.com/1/urls/count.json".
   return isset($ar[2]) ? $ar[2] : 0;

Then use the following code within the loop to display how many times the current post has been shared on Twitter:

echo readTwitterShares(get_permalink());

Source: http://www.barattalo.it/2012/10/19/how-many-times-a-web-link-has-been-shared…

Add Twitter and Facebook info fields

By default, WordPress allows you to add various contact info as such as Jabber, AIM and Yahoo Messenger. But there’s no way to add your Twitter and Facebook info. Here’s a handy code snippet to remove the mostly useless YIM, AIM and Jabber and add Twitter and Facebook info instead.

This code goes to your functions.php file.

function new_contactmethods( $contactmethods ) {
    $contactmethods['twitter'] = 'Twitter'; // Add Twitter
    $contactmethods['facebook'] = 'Facebook'; // Add Facebook
    unset($contactmethods['yim']); // Remove YIM
    unset($contactmethods['aim']); // Remove AIM
    unset($contactmethods['jabber']); // Remove Jabber

    return $contactmethods;

Source: http://wp-snippets.com/addremove-contact-info-fields

  • Hi, thanks for this tips ! I get an error when using the “Display your latest tweet” code :

    Fatal error: Call to undefined method WP_Error::get_item_quantity() in /homez.402/myleneb/www/wp-content/themes/myleneb/footer.php on line 7

    Can you help me, please ?

  • Thanks for this post…I think Open graph feature readily comes with installing SEO by Yoast plugin. Displaying fav. tweets is my fav snippet in above list.

  • Thanks for the useful code Jean-Baptiste, although I wouldn’t personally recommend going overboard with embedding social widgets on your website. Remember that social networks should be for building traffic to your website, not the other way round.

  • this post is really nice. You’re all the tips are helpful thanks for sharing…

  • Stumbled upon the post at the right time ! bookmarked the post. will use it on my projects.

  • Can’t you just take the codes from Twitter to dislay tweets? Smack it into a textwidget, and voila, job done 😉

  • The functions for Displaying how many times a post has been shared on twitter, is really useful: I’ve been using the “official” tweet button principally because it includes that functionality, which didn’t appear to be easy to replicate, but now knowing that it can be done with a function like this is making me reconsider: I can drop a JS file then…

  • Hello,

    this very good article, especially the code you provide, I think more than one serve me for a web out there that I have neglected for some time and I want to return.

    Truly thank you very much for taking the time!

    greetings and a very strong hug from Mexico

  • Very nice, this website will be my reference

  • Thanks for compiling this snippets. Sometimes a WP plugin has valuable features and may be a better option. I use Share & Follow and Slick Social Share Buttons.

  • i use pin-it and like it alot. Maybe the google plus could work well, i will have to look into that.