Site icon Mostly Harmless

Easy Twitter Button for WordPress

Twitter announced their own Tweet Button and have provided a page for creating a button on your web site. You enter some info and you get the HTML code to add.

Extending WordPress has always been easy. You can add what you want via a plugin, or you can put the functionality into your theme’s function.php file.

I wanted to play around with adding this to my blog, so I went to their page and created my button. I then used the generated code as a template for what I wanted to do.

There is no way I’m savvy enough to write a plugin, but adding a filter to my theme’s function.php file is within my reach.

This is from an idea I got when I read WP Beginner’s post on how to add post thumbnails to your RSS feed. I used his code to do this.

function tweet_button($content) {
        global $post;
        // Your Twitter ID goes here
        $twitterid = 'jan_dembowski';
        $tweetbutton = '<div class="tweet-button">';
        $tweetbutton = $tweetbutton . '<a href="http://twitter.com/share" class="twitter-share-button" data-url="' . get_permalink() .'" data-text="' . get_the_title() .'" data-count="horizontal" data-via="' . $twitterid . '">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>';
        $tweetbutton = $tweetbutton . '</div>';
        // $content = $content . $tweetbutton;
        $content = $tweetbutton . $content;
        return $content;
        }
add_filter('the_content', 'tweet_button');

You can download the code via this text file link.

It’s not exactly user friendly, but it gets the job done. I wrapped it in a <div> so I can style it later. If you want the button at the end instead of the beginning, then comment out line 9 and un-comment out line 8.

It’s a fun hack for me and I am sure that soon there will be a plugin to do this. If you do decide to do this then make sure you backup your theme’s function.php file. Any typo’s or mistakes will make your WordPress blog stop working.

Exit mobile version