Created
May 19, 2023 02:36
-
-
Save AndroPlus-org/305bc316f91bcd6ade81242e708f04d3 to your computer and use it in GitHub Desktop.
Twitter API v2 WordPress 投稿時に自動ツイート
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://github.com/fsyhrnl/twifer | |
を | |
composer require ferrysyahrinal/twifer | |
でテーマフォルダにインストールしておく | |
<?php | |
require_once STYLESHEETPATH . '/vendor/autoload.php'; | |
use Twifer\API; | |
function tweetv2($new_status, $old_status, $post){ | |
// 投稿のときのみ & 投稿ステータスが公開以外から公開になったときのみ | |
if($post->post_type == 'post' && $new_status == 'publish' && $old_status != 'publish'){ | |
$conn = new API('CONSUMER_KEY', 'CONSUMER_SECRET', 'OAUTH_TOKEN', 'OAUTH_TOKEN_SECRET'); | |
// 文字数上限に合わせるため余裕を持って残り文字数を計算 | |
$count = 137 - mb_strwidth('✨'); | |
// ツイート本文 → 投稿タイトルとパーマリンク | |
$text = '✨' . mb_strimwidth($post->post_title, 0, $count, "...") . ' ' . get_the_permalink($post->ID); | |
// ツイートする | |
$postfields = "{\"text\":\"$text\"}"; | |
$res = $conn->request('POST', '/2/tweets', $postfields); | |
} | |
} | |
//transition_post_statusは記事のステータス(公開や下書きなど)が変わった時に発動 | |
add_action('transition_post_status', 'tweetv2',10,3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment