Created
December 10, 2010 06:56
-
-
Save taiju/735885 to your computer and use it in GitHub Desktop.
WordpressでTweetThisボタンを組み込むときにリンクを生成する関数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function the_tweet_this($template) { | |
global $post; | |
$base_uri = 'http://api.bit.ly/v3/shorten'; | |
$params = array( | |
'login' => YOURLOGINID, | |
'apiKey' => YOURAPIKEY, | |
'format' => 'json', | |
); | |
$params['longUrl'] = urlencode(get_permalink($post)); | |
$paramsmap = array(); | |
foreach ($params as $key => $value) { | |
array_push($paramsmap, "$key=$value"); | |
} | |
$request_uri = $base_uri . '?' . join('&', $paramsmap); | |
$json = file_get_contents($request_uri); | |
$php_json = json_decode($json); | |
$replaced = $template; | |
if (preg_match_all("/{\s*(\w+)\s*}/", $template, $matches)) { | |
foreach ($matches[1] as $key) { | |
switch ($key) { | |
case 'title': | |
$replaced = preg_replace("/{\s*title\s*}/", get_the_title($post), $replaced); | |
break; | |
case 'longUrl': | |
$replaced = preg_replace("/{\s*longUrl\s*}/", $params['longUrl'], $replaced); | |
break; | |
} | |
} | |
} | |
if ($php_json->status_code === 200) { | |
if (preg_match("/{\s*shortUrl\s*}/", $template)) { | |
$replaced = preg_replace("/{\s*shortUrl\s*}/", $php_json->data->url, $replaced); | |
} | |
} | |
else { | |
if (preg_match("/{\s*shortUrl\s*}/", $template)) { | |
$replaced = preg_replace("/{\s*shortUrl\s*}/", $params['longUrl'], $replaced); | |
} | |
} | |
echo "http://twitter.com/home/?status=" . urlencode($replaced); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
使い方
Wordpressループ中に使います
下準備
$params
のlogin
とapiKey
にbit.lyのログインIDとAPIキーを設定しておくパラメータ
$template
出力したい文字列を指定。以下の変数を利用可能。
{title}
ブログ記事タイトル
{longUrl}
パーマリンク
{shortUrl}
bit.lyのショートリンク
その他
関数で文字列を取得するなどで必要な情報を埋め込む
サンプルコード