WordPressからTwitterへの自動投稿(途中)

API

目的

WordPressの記事を投稿したらTwitterに自動でポストされるようにしたい

TwitterOAuthライブラリ

https://github.com/abraham/twitteroauth】からDownload Zipします。

解凍してファイル名をtwitteroauthにリネームします。

WordPressのテーマディレクトリ直下にファイルをアップロードします。

PHP Versionの変更

ConohaのコントロールパネルでウェブサイトのPHPバージョンを7.4 -> 8.0に変更します。

TwitterOAuth.phpのコードはPHP8.0以降にしないと動きません。

バージョンを変更しないと記事を投稿した瞬間に次のエラーが発生します。

「syntax error, unexpected ‘)’, expecting variable (T_VARIABLE) in TwitterOAuth.php on line 58」

functions.php

define('TWITTER_CONSUMER_KEY', 'あなたのAPIキー');
define('TWITTER_CONSUMER_SECRET', 'あなたのAPISecret');
define('TWITTER_ACCESS_TOKEN', 'あなたのAccessToken');
define('TWITTER_ACCESS_TOKEN_SECRET', 'あなたのAccessTokenSecret');

use Abraham\TwitterOAuth\TwitterOAuth;
function post_to_twitter($post_ID) {
	$post_title = get_the_title($post_ID);
	$post_url = get_permalink($post_ID);
	$message = '新着記事:' . $post_title . '' . $post_url;
	
	require_once get_template_directory() . '/twitteroauth/autoload.php';
	
	// make instance
	$twitteroauth = new TwitterOAuth(
		TWITTER_CONSUMER_KEY,
		TWITTER_CONSUMER_SECRET,
		TWITTER_ACCESS_TOKEN,
		TWITTER_ACCESS_TOKEN_SECRET
	);
	
	// post to twitter
	$response = $twitteroauth->post(
		'statuses/update',
		['status' => $message]
	);
	
	// error
	if ($twitteroauth->getLastHttpCode() != 200) {
		error_log('Twitter API Error: ' . print_r($response, true));
	}
	return $post_ID;
}
add_action('publish_post', 'post_to_twitter');
add_action('publish_page', 'post_to_twitter');

BACK