UPDATE Jan 6 2012: While the code should still work, I have disabled this approach on my own blog, instead using the Sharing tool built into the JetPack plugin.
Twitter has created a new widget that makes it more friendly to provide a tweet this button from your own web sites, blogs, etc. The benefit is that it pops a window up with the twitter functionality, so you are not sending people from the web site.
See the announcement from the twitter blog to learn more. The tweetbutton creation widget makes it easy to generate the code, and has a umber of options to choose from for the appearance of the button and what gets prefilled in the tweet (plus with their new url shortener t.co is one letter shorter than competitors!).
This works well on a WordPress single post template, where it pulls the url for the current page and provides a tweet button where-ever you like it. I put mine in the header tag that displays the blog post.
I also want on my main index page and archives where there are multiple posts. Here is how I set it up.
This way we only load this library once, and now can use the code on any web page.
<h1 class="entry-title"><?php the_title(); ?> <a href="http://twitter.com/share" class="twitter-share-button" data-count="none" data-via="cogdog">Tweet</a></h1>
That was easy.
But I wanted more- I would like it on each post on the front of my blog.
That is also easy.
For the main page template, index.template, we cannot use the basic code because it posts the URL and title for the current page in view (just my blog) rather than for each post in the loop. This is easily rectified using the WordPress loop variables, so inside my loop where it is moving through posts, I have:
<h2 class="entry-title"><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permalink to <?php the_title(); ?>"><?php the_title(); ?></a> <a href="http://twitter.com/share" class="twitter-share-button" data-url="<?php the_permalink(); ?>" data-count="none" data-text="<?php the_title(); ?>" data-via="cogdog">Tweet</a></h2>
so I am populating the data-url and the data-text fields with the permalink and post title as WordPress moves through the loops. Try it out on http://cogdogblog.com/ – each post title has its own tweet this button.
I can now add this to archives, search result templates etc.
I like the functionality and am looking at rolling it as well into our NMC fleet of web sites.
The Rolling New Tweet Button into WordPress by CogDogBlog, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.