[Tips] 投稿時画像付き自動SNSアップ(Twitter版)(WordPress)

いままで『WordTwit Twitter Plugin』を使って投稿時の自動ツイートを実施していました。
画像をアップしたくて四苦八苦した挙句、固定の画像をアップするようにはしました。
(こんな感じ↓)


ただ、毎回ブログをアップする際の画像が固定となり、これを変えるとなるとそれはそれで一苦労(Twitterに一度画像を上げて画像URLをコピーして投稿時に貼り付け)でした。

プラグインで良いのがないか色々探したのですが、自分に合うものがなかったため今回は下記サイトを参考し埋め込むことにしました。

上記サイトを参考にして作ったソースが以下。
function.phpに入れます。
「tmhOAuth.php」をあらかじめ入手後function.php配下の「func」フォルダ(ない場合は作成)に配置します。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//公開時にツイート
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 追加]
また、過去記事のランダム投稿方法もありましたので、追加しました。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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

過去の晒すと投稿したイラストとかがないのが多いですね。
(折を見て修正していかないとかな…)

おすすめ

記事に関する商品の広告を表示しています。気になった商品があれば確認してみてください。

  • x
  • pixiv
  • pixivFANBOX
  • skeb
  • amazon
  • booth
  • nijie
  • pixivSKETCH
  • Patreon
  • YouTube

関連記事

  1. READ MORE

    [Tips] プラグイン『Adminer』(Word...

    2016-10-04

  2. READ MORE

    [Tips] WordPress管理画面にログインで...

    2020-05-04

  3. READ MORE

    [Tips] プラグイン 「Twitter Widg...

    2011-04-30

  4. READ MORE

    [Tips] 予約投稿(WordPress)

    2014-04-27

CALENDAR

2025年3月
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

RECOMMEND POST

  1.    

    READ MORE

    [日記] イヤホン

    投稿日:2010-10-29

    今使ってるBLUETOOTH対応イヤホンです。

ADVERTISEMENT

ARCHIVE

THE WORK

GALLERY

  1. READ MORE

    更新日:2022-02-06

    オープンエロなお姉さんとお節介焼きのエルフ少女、彼女たちに振り回されるラッキースケベ魔法使い男がいます。

  2. READ MORE

    更新日:2022-01-11

    40代主婦と10代JKの母娘が近所の冴えない青年に寝取られて、楽しいS●Xライフを送る毎日

  3. READ MORE

    更新日:2021-12-14

    エルフ族・竜族・猫族の3人美人義姉妹が教会のシスターとしておりなすお悩み解決エロファンタジー

  4. READ MORE

    更新日:2020-07-13

    arohaJ様のpixiv内企画「pixivファンタジア」に参加した際のイラストです。

  5. READ MORE

    更新日:2023-12-11

    pixivの企画参加絵や取り留めなく書いた落書き、まだグループとして外出しできないようなモノを入れています。まぁ一言で言えばなんだかよく分からないということです

  6. READ MORE

    更新日:2024-09-07

    お気に入り:『ワンピース』『NARUTO』『BLEACH』『鋼の錬金術師』『ダイの大冒険』『生徒会役員共』

  7. READ MORE

    更新日:2023-03-05

    pixivやtwitterなんかでお知り合いになった絵師さんのお子さんを描かせていただきました。

  8. READ MORE

    更新日:2022-05-02

    たまにお出掛けしたときに撮った写真やマイ猫の記録写真などです。

ページ上部へ戻る