(+84) 463.28.7979

Show Tweetmeme Button on Selected WordPress Posts


Tweetmeme is a Digg-like site for popular links on Twitter. Using a Tweetmeme badge can be a helpful reminder for your readers to retweet it – and if my experience is anything to go by, Twitter does send targeted traffic to your blogs. Clicking on the Tweetmeme badge will direct you to your Twitter profile, with a tweet of the format RT @tweetmeme <post title> <post link>.

Integrating Tweetmeme on your blog is as simple as entering some JavaScript code (provided on Tweetmeme website). In this WordPress hack, however, I’ll show you how to display the Tweetmeme button only on posts you decide – by using a custom field. This is crucial, because a Tweetmeme badge on a site announcement would be unprofessional, not to mention redundant.

PHP function to to display Tweetmeme badge

Since you would want to show the Tweetmeme badge on multiple pages (on single.php, index.php etc.), wrapping the code in a simple function is a good idea. We can then call this function wherever we want the badge to be displayed.

Open up your theme’s functions.php file. At the end of the file, you will find a ?>

Place the code below just before that.

function tweetmeme(){
?>
<div style="float: left; margin: 5px 15px 5px 0;">
<script type="text/javascript">
tweetmeme_url = '<?php the_permalink(); ?>';
</script>
<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>
</div>
<?php
}

PHP tag to display the badge

In single.php and index.php, place the code below just before the tag <?php the_content(); ?> or <?php the_excerpt(); ?>.

<?php $check_sm = get_post_meta($post->ID, 'tweetmeme', $single = true);
if($check_sm != '')
tweetmeme();
?>

Enabling the badge on posts

Enabling the Tweetmeme badge requires you to add a custom field to the post in question. On posts where you want to display the post, add a field named tweetmeme with a value true.

You can also extend this hack to hide Tweetmeme badge only on posts where you enter a custom field, or show other badges (Digg, Stumble Upon etc.) selectively.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>