Skip to content

Instantly share code, notes, and snippets.

@taiju
Created December 10, 2010 06:56
Show Gist options
  • Save taiju/735885 to your computer and use it in GitHub Desktop.
Save taiju/735885 to your computer and use it in GitHub Desktop.
WordpressでTweetThisボタンを組み込むときにリンクを生成する関数
<?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);
}
@taiju
Copy link
Author

taiju commented Dec 10, 2010

使い方

Wordpressループ中に使います

下準備

$paramsloginapiKeyにbit.lyのログインIDとAPIキーを設定しておく

パラメータ

$template

出力したい文字列を指定。以下の変数を利用可能。

  • {title}

    ブログ記事タイトル

  • {longUrl}

    パーマリンク

  • {shortUrl}

    bit.lyのショートリンク

  • その他

関数で文字列を取得するなどで必要な情報を埋め込む

サンプルコード

<a href="<?php the_tweet_this('"{title}" - BLOGNAME {shortUrl} #mysite'); ?>"><img src="image/tweetthis.gif" alt="tweet this."></a>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment