I know there are third party programs out there such as AddThis but I like to do things myself and have better control. This code probably could be cleaned up a bit(I just put things together from what I found on Google) but it works. If anyone feels like cleaning up the code a bit, please feel free.
What this code does is add a link to a product's page that allows the user to quickly and easily Tweet about the product and include a link back to the product page. Because of the 140 character limit, the current page link is sent to a link shortening site (
http://www.bit.ly in this case) to shorten it before using it in the Tweet. As such, you'll need to create a free account a bit.ly so you can fill in your own details below. This will also allow you to track the links being shortened and how many clicks they get through the bit.ly interface.
Here's the code. I put this beneath my Add to Cart button in product.tpl
Code:
{php}
function getBitlyUrl($url) {
$bitlylogin = 'PUT_YOUR_BITLY_LOGIN_NAME_HERE';
$bitlyapikey= 'PUT_YOUR_BITLY_API_KEY_HERE';
$bitlyurl = file_get_contents("http://api.bit.ly/shorten?version=2.0.1&longUrl=".$url."&login=".$bitlylogin."&apiKey=".$bitlyapikey);
$bitlycontent = json_decode($bitlyurl,true);
$bitlyerror = $bitlycontent["errorCode"];
if ($bitlyerror == 0) {
$bitlyurl = $bitlycontent["results"][$url]["shortUrl"];
}
else $bitlyurl = "error";
return $bitlyurl;
}
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
{/php}
<a href="http://twitter.com/home?status=I'm liking this {$product.product} from @PUT_YOUR_TWITTER_ID {php}echo getBitlyUrl((curPageUrl())){/php}" target="_blank">Share on Twitter</a>
You can put pretty much say whatever after the
http://twitter.com/home?status= part above. What I have will pre-fill the user's Twitter post box with:
I'm liking this PRODUCT_NAME from @MYTWITTERACCOUNT SHORT_URL_BACK_TO_PRODUCT_PAGE
You might want to say something similar or depending on your products maybe something like
Checking out PRODUCT_NAME at SHORT_URL_BACK_TO_PRODUCT_PAGE - What do you guys think?
etc.