Modern Optimist

Add a Tweet Button to each Post in a WordPress Archive page

After not finding a simple solution online, I recently put this simple job on oDesk and got back quotes for 3hrs, 5hrs etc. Surely it’s a couple lines of code I thought. So I took time this morning with a fresh head, tackled it and it landing up being super easy. Here’s a 1 minute tutorial.

Basically you just slam in the WordPress code in the custom ‘Title’ and ‘URL’ fields in the Twitter code generator on their site.

Title

Wordpress call for pulling the post title

URL

Wordpress call for pulling the post URL

This generates this code (has comments):

<a href="http://twitter.com/share"
class="twitter-share-button" 

data-url="<?php the_permalink() ?>"  // Grabs post URL

data-text="<?php the_title(); ?>" // Grabs post title

data-count="horizontal" data-via="YourName"> // Use your own Twitter username

Tweet // What you want the button to say

</a>
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>

Here is the code without comments, copy this one:

<a href="http://twitter.com/share"
class="twitter-share-button"
data-url="<?php the_permalink() ?>"
data-text="<?php the_title(); ?>"
data-count="horizontal" data-via="YourName">
Tweet
</a>
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>

Then remember to insert the code in your archive page in the loop, like:

<?php while (have_posts()) : the_post(); ?> 

// Inside the loop starts here

<a href="http://twitter.com/share" class="twitter-share-button" data-url="<?php the_permalink() ?>"  data-text="<?php the_title(); ?>" data-count="horizontal" data-via="YourName"> Tweet </a> <script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>

And you’re done! Should look something like this below:
cf

4 Comments

  1. Dave Jenkins says:

    Cheers, good tut.

  2. prakash says:

    hi, i tried the above method, i added my username of the twitter site in data-vai section, it allows to share but the count do not change, any help would be appreciated

Leave a Reply