wordpress
WordPress 怠け者向け、Autoshare for twitterでの自動投稿でタグに#を付けて投稿させる
最終更新日: 2025年2月26日
色々管理とかやってると、WPでタグは付けても「カスタムメッセージ」にハッシュタグ入れ忘れるんだわ。
今のTwitterAPI2.0では自動投稿する手法が狭められたが、
- 連携ライブラリを使いサーバーのcronで時間調整する自動投稿
- WPのプラグインautoshare for twitter(今はxだけど)での即時自動投稿
このどちらかを使ってる。
他にIFTTTやらいくつかあるが、WPの場合即時が良いからプラグイン、開発停まったり使えなくなったら連携ライブラリ、Twitterでは実装したことないけど他では使ってるIFTTTで保険かける感じかな。
イーロンのやり方に文句はあるが、なんだかんだ呟くのが一番なんだわ。Meta社のものとか(たまにinsta使ってるしFBもThredsもアカウントあるけど、個人的にはね)要らん。
とりまTwitterには連携させたい、こちらMovableTypeもやってるから、連携ライブラリをサーバーにインストールさせたりもしている。
連携ライブラリのやつはcronで叩くファイルも作るから、投稿内容の何を呟くか、もちろんタグをハッシュ付けてとかOKだが、PLはそうはいかない。
使う人によってはタグを勝手に#つけて呟かれるとか迷惑だろうしね。
まぁ、ここでは楽したい人向け、プラグインの改造。
弄るのはプラグインディレクトリ/include/utils.php。
これの
/**
* Allow filtering of tweet body
*/
/*
$tweet_body = apply_filters( 'autoshare_for_twitter_body', get_tweet_body( $post->ID ), $post );
*/
/**
* Allow filtering of post permalink.
*
* @param $permalink
*/
/*
$url = apply_filters( 'autoshare_for_twitter_post_url', get_the_permalink( $post->ID ), $post );
$url = esc_url( $url );
$body_max_length = 275 - strlen( $url ); // 275 instead of 280 because of the space between body and URL and the ellipsis.
$tweet_body = sanitize_text_field( $tweet_body );
$tweet_body = html_entity_decode( $tweet_body, ENT_QUOTES, get_bloginfo( 'charset' ) );
$tweet_body_length = strlen( $tweet_body );
$ellipsis = ''; // Initialize as empty. Will be set if the tweet body is too long.
while ( $body_max_length < $tweet_body_length ) {
// We can't use `…` here or it will display encoded when tweeting.
$ellipsis = ' ...';
// If there are no spaces in the tweet for whatever reason, truncate regardless of where spaces fall.
if ( false === strpos( $tweet_body, ' ' ) ) {
$tweet_body = substr( $tweet_body, 0, $body_max_length );
break;
}
// Otherwise, cut off the last word in the text until the tweet is short enough.
$tweet_words = explode( ' ', $tweet_body );
array_pop( $tweet_words );
$tweet_body = implode( ' ', $tweet_words );
$tweet_body_length = strlen( $tweet_body );
}
return sprintf( '%s%s %s', $tweet_body, $ellipsis, $url );
}
この部分を
$title = get_the_title( $post );
$url = wp_get_shortlink($post->ID);
// ハッシュタグ付きのタグを取得
$tags = get_the_tags( $post );
$hashtag_string = '';
if ( $tags && !is_wp_error($tags) ) {
$hashtag_array = array_map( function ( $tag ) {
return '#' . $tag->name;
}, $tags );
$hashtag_string = implode( ' ', $hashtag_array );
}
// ツイート本文を組み立てる(短縮URLを使用)
$tweet_body = $title . ' ' . $hashtag_string . ' ' . $url;
return trim($tweet_body);
}
これに差し替えてファイルを上書きすればよい。
もちろん、プラグインのアプデ行えば消えると思う。動作はAutoshare for twitter 2.0で確認。2.1から上は、php8・Sql5か8、wp5.9~6.7で使えたことがないので古いまんま。
多分最新2.3でも然るべき書き換えすれば使えるのではないかと思うが、チャレンジャーであればバックアップ取ってやってみるのもいいかも。