いままで『WordTwit Twitter Plugin』を使って投稿時の自動ツイートを実施していました。
画像をアップしたくて四苦八苦した挙句、固定の画像をアップするようにはしました。
(こんな感じ↓)
ブログを更新しました。⇒ 投稿: [日記] 男子400Mリレー(リオ五輪) – https://t.co/Q8eFysfGkP https://t.co/TscyR0F7ak
— しゃとら🐈🎨 (@shatla) August 20, 2016
ただ、毎回ブログをアップする際の画像が固定となり、これを変えるとなるとそれはそれで一苦労(Twitterに一度画像を上げて画像URLをコピーして投稿時に貼り付け)でした。
プラグインで良いのがないか色々探したのですが、自分に合うものがなかったため今回は下記サイトを参考し埋め込むことにしました。
- WordPressで記事を公開した時に自動で画像付きツイートを行う方法 | Wood-Roots.blog
- tmhOAuthで画像付きつぶやきをする方法 | 丸ノ内テック
ベースはこちらを採用させていただきました。シンプルで分かりやすかったです。
ベースの画像投稿処理がtwitterでは非推奨ということなので、画像投稿処理部分をこちらを参考に変えました。
上記サイトを参考にして作ったソースが以下。
function.phpに入れます。
「tmhOAuth.php」をあらかじめ入手後function.php配下の「func」フォルダ(ない場合は作成)に配置します。
//公開時にツイート
function tweetImage($new_status, $old_status, $post){
//tmhOAuth.phpをhttps://github.com/themattharris/tmhOAuthよりダウンロードしてテンプレートフォルダ内に入れておく
require_once TEMPLATEPATH.'/func/tmhOAuth.php';
//よくあるアクションフックと違い、$postはIDではなくpostオブジェクトそのものになるようです。なのでget_post不要
//ステータスが「publish」(公開)になったとき。$new_statusだけの判定だと更新ボタンを押しただけでツイートされてしまうので「publishじゃない記事」が「publishになったとき」にツイートするようにしている
if($new_status == 'publish' && $old_status != 'publish'){
//トークンなどの設定
$tmhOAuth = new tmhOAuth(array(
"consumer_key" => 'APIキー',
"consumer_secret" => 'APIシークレット',
"user_token" => 'アクセストークン',
"user_secret" => 'アクセストークンシークレット',
'curl_ssl_verifypeer' => false //SSL対応に必要
));
//ツイートするテキスト(字数は定型文やハッシュタグを使う場合は適宜調整が必要)
//ここでは「ブログ書きました:記事タイトル... URL #カテゴリ名」というフォーマットにしています
//カテゴリ名取得
//カテゴリ名をハッシュタグにしている
$cat = get_the_category($post->ID);
$cat_text = '';
foreach($cat as $val){
$cat_text .= ' #' . $val->name;
}
//アイキャッチ取得
$file = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' );
//アイキャッチがなかったらダミー画像を入れとく
//ない場合は画像添付なしでツイートするとか、カテゴリによってダミー画像を切り分けるなど一考の余地がある
if($file){
$file = $file[0];
} else {
$file = 'https://www.a-legend.net/images/logo_500x500.png';
}
$image = file_get_contents( $file );
$imagesize = getimagesize( $file );
//文字数計算(140-「ブログ書きました:」 - 「...」- ハッシュタグ文字数 - 短縮URLの文字数(半角23文字))
//だが、念のため130文字で収まるようにしている
$count = 130-mb_strlen('ブログ更新しました:')-mb_strlen($cat_text)-23;
//画像の準備をします
$upload_image = base64_encode($image);
$update_img_params = array(
'media_data' => $upload_image
);
$code_img = $tmhOAuth->request(
'POST',
'https://upload.twitter.com/1.1/media/upload.json',
$update_img_params,
true,
true
);
$result_img = json_decode($tmhOAuth->response["response"], true);
$result_media_id = $result_img['media_id_string'];
//ツイートする
$update_params = array(
'media_ids' => $result_media_id,
'status' => mb_strimwidth('ブログ書きました:'.$post->post_title, 0, $count, "...") . ' ' . get_permalink($post->ID) . $cat_text
);
$code = $tmhOAuth->request(
'POST',
'https://api.twitter.com/1.1/statuses/update.json',
$update_params
);
}
}
//アクションフック
//transition_post_statusは記事のステータス(公開や下書きなど)が変わった時に発動します
add_action('transition_post_status', 'tweetImage',10,3);
結果こんな感じになります。
https://twitter.com/shatla/status/766938176724148224
[2016/9/10 追加]
また、過去記事のランダム投稿方法もありましたので、追加しました。
function tweetPost(){
//tmhOAuth.phpをhttps://github.com/themattharris/tmhOAuthよりダウンロードしてテンプレートフォルダ内に入れておく
require_once TEMPLATEPATH.'/func/tmhOAuth.php';
//トークンなどの設定
$tmhOAuth = new tmhOAuth(array(
"consumer_key" => 'APIキー',
"consumer_secret" => 'APIシークレット',
"user_token" => 'アクセストークン',
"user_secret" => 'アクセストークンシークレット',
'curl_ssl_verifypeer' => false //SSL対応に必要
));
//ツイートする記事の取得
//いつものget_postsなので、ここでツイートしたい記事の条件をいろいろ指定できる。
$post = get_posts(array(
'numberposts' => 1,
'orderby' => 'rand'
));
//カテゴリ名取得
//カテゴリ名をハッシュタグにしている
$cat = get_the_category($post[0]->ID);
$cat_text = '';
foreach($cat as $val){
$cat_text .= ' #' . $val->name;
}
//アイキャッチ取得
$file = wp_get_attachment_image_src( get_post_thumbnail_id($post[0]->ID), 'thumbnail' );
//アイキャッチがなかったらダミー画像を入れとく
//ない場合は画像添付なしでツイートするとか、カテゴリによってダミー画像を切り分けるなど一考の余地がある
if($file){
$file = $file[0];
} else {
$file = 'https://www.a-legend.net/images/logo_500x500.png';
}
$image = file_get_contents( $file );
$imagesize = getimagesize( $file );
//文字数計算(140-「【過去記事】」 - 「...」- ハッシュタグ文字数 - 短縮URLの文字数(半角23文字))
//だが、念のため130文字で収まるようにしている
$count = 130-mb_strlen('【過去記事】')-mb_strlen($cat_text)-23;
//画像の準備をします
$upload_image = base64_encode($image);
$update_img_params = array(
'media_data' => $upload_image
);
$code_img = $tmhOAuth->request(
'POST',
'https://upload.twitter.com/1.1/media/upload.json',
$update_img_params,
true,
true
);
$result_img = json_decode($tmhOAuth->response["response"], true);
$result_media_id = $result_img['media_id_string'];
$update_params = array(
'media_ids' => $result_media_id,
'status' => mb_strimwidth('【過去記事】'.$post[0]->post_title, 0, $count, "...") . ' ' . get_permalink($post[0]->ID) . $cat_text
);
$code = $tmhOAuth->request(
'POST',
'https://api.twitter.com/1.1/statuses/update.json',
$update_params
);
}
//Cronへ登録
add_action('tweetcron', 'tweetPost');
function my_activation() {
if ( !wp_next_scheduled( 'tweetcron' ) ) {
wp_schedule_event(time(), 'twicedaily', 'tweetcron');
}
}
add_action('wp', 'my_activation');
WP-Cronへの登録は1日2回設定(twicedaily)にしています。
これは「hourly(1時間ごと)」、「daily(1日ごと)」の3種類のみになります。
もう少し設定値増やしてほしいですね。
https://twitter.com/shatla/status/774759382537998337
過去の晒すと投稿したイラストとかがないのが多いですね。
(折を見て修正していかないとかな…)