How To Create A Dynamic “Tweet This Button” With PHP

Yesterday I have just released some of my graphics for Twitter that I have designed myself.

This time I will show you how can easily create links to your own pages on your website or different articles whenever you have both a page URL and a page title available.
This code automatically removes characters from the end of the title so that in addition to the URL itself and a space character between the maximum length of 140 characters will not be exceeded. If the title is too long it will be truncated and three dots will be appended to show that it has been shortened.

When clicking on the link the user is taken to the Twitter homepage with the message already preset so that he can tweet it immediately with just a single click.

function getTweetUrl($url, $title)
{
$maxTitleLength = 140 - (strlen($url)+1);
if (strlen($title) > $maxTitleLength) {
$title = substr($title, 0, ($maxTitleLength-3)).'...';
}
$output = "$title $url";
return 'http://twitter.com/home?status='.urlencode($output);
}
?>
Example usage:
<a href="<?php echo $url; ?>" target="_blank"><img src="tweetthis.gif" border="0" alt="Tweet This!" /></a>

tweetthis-15

Share and Enjoy:
  • DZone
  • del.icio.us
  • Digg
  • StumbleUpon
  • Mixx
  • TwitThis
  • Technorati
  • FriendFeed
  • Google Bookmarks
  • BlinkList
  • blogmarks
  • Furl
  • LinkArena
  • Live
  • MySpace
  • NewsVine
  • Ping.fm
  • Reddit
  • Simpy
  • Spurl
  • Identi.ca
  • LinkedIn
  • MisterWong
  • Slashdot
  • Sphinn
  • Yahoo! Bookmarks
  • Facebook
  • RSS
  • Turn this article into a PDF!
  • Print this article!

Tags: , ,

5 Responses to “How To Create A Dynamic “Tweet This Button” With PHP”

  1. Rhonda G says:

    Great Page Brother.

    I downloaded the buttons. Thank you for the gift of giving up front.

    I will keep an eye on what you are doing and do a write up on you in the very near future!

    Rhonda Giarraffa
    Affiliate Review Guru
    http://www.affiliatereviewguru.com

  2. Peter Elsner says:

    This won’t work. No where in your example do you actually call the getTweetUrl() function

    So, what will happen is absolutely nothing when the link is clicked. Just an FYI.

  3. Peter Elsner says:

    Nevermind what I just said. I see what the script is supposed to do :) I was reading the description as to what it was supposed to do incorrectly…

  4. DeZiner76hd says:

    This is a great script and so is your html script. The html script I can get working the php script I am confused on how to implement it. Where does the actual fuction go so it can be called?
    Thank you
    DeZiner

  5. Great script. Thanks. And if you add onclick=”w=window.open(this.href,\’tweet\’,\’width=800,height=450,scrollbars,resizable,left=0,top=0\’); w.focus(); return false;\”
    between the a and href, and remove the target=blank, you can get it to open in a popup window instead.

    Best wishes

    Tony

Leave a Reply