Wordpressでプラグインを使わずにtwitterへ自動ツイートを実装してみる

TwitterOAuthライブラリ を使用している
ライブラリ使用方法の参考記事:PHP+OAuthでTwitter

TwitterへOAuthクライアントの登録

TwitterにOAuthアプリケーション情報を登録。アプリケーション登録等の手順は割愛。
Twitter Applications | dev.twitter.com

Twitterに過去記事を自動POSTする機能を実装

仕様

登録されている記事からランダムで1件取得しツイートするシステム
現在、期間指定などしていない
ツイートの間隔は、6時間に1ツイート

ライブラリのダウンロード

TwitterOAuthライブラリを以下の場所へ保存

/path/to/wordpress/themes/example/libs/components/
自動ツイートまで

→ クローンで実行されるファイル

ツイッターへPOSTを実行するクラス

  • /path/to/wordpress/themes/example/libs/components/twitteroauth/twitteroauth.php

Twitter OAuth ライブラリ本体

tweet_post_cron.php

<?php
// wordpress関数を使用できるように読み込む
require_once('/home/www/htdocs/zukunasi.net/wp-load.php');
// ツイッターへのポストを実行するクラスを読み込む
require_once (get_theme_root() . '/' . get_template() . '/libs/twitter.class.php');
// 短縮URLを取得するクラスを読み込む
require_once (get_theme_root() . '/' . get_template() . '/libs/bitly.class.php');

$twitter=new TwitterClass();       
$bitly=new BitlyClass();           

// query...                        
global $wpdb;                      
$query="select ID, post_title from wp_posts where post_status = 'publish' and post_type = 'post' order by rand() limit 1;";
$post=$wpdb->get_row($query);
$before='[過去記事]:';            
$url=get_permalink($post->ID);
// bit.ly api...
$url=$bitly->__createShortUrl($url);
$string=$before.$post->post_title.' - '.$url;
if( strlen($string) > 140 ) {      
    mb_substr($string, 0, 140);    
} 
// tweet...
$twitter->__tweet($string);

twitter.class.php

<?php
// 設定ファイルを読み込む
require_once (get_theme_root() . '/' . get_template() . '/config.php');
// Twitter OAuth ライブラリを読み込む
require_once (get_theme_root() . '/' . get_template() . '/libs/components/twitteroauth/twitteroauth.php');
class TwitterClass {

    var $twitter;

    function __construct() {
        $this->twitter=new TwitterOAuth(
            TWITTER_CONSUMER_KEY,
            TWITTER_CONSUMER_SECRET,
            TWITTER_ACCESS_TOKEN_KEY,
            TWITTER_ACCESS_TOKEN_SECRET
        );
    }

    function __tweet($string) {
        return $this->twitter->OAuthRequest(
            "http://api.twitter.com/1/statuses/update.xml",                                                                                                                                   
            "POST",
            array("status"=>$string)
        );  
    }   
}

最後にクーロンを設定して完了。