雑記帳

整理しない情報集

WordPressの記事投稿/更新時にDiscordへメッセージを送信する

公開日:

カテゴリ: WordPress

DiscordにはWebhookという機能があり、指定されたURLにPOSTデータを送信するだけで簡単にメッセージを送信できます。今回はWordPressの記事を投稿した時と更新した時にDiscordへメッセージを送信させてみます。

事前準備

Discord Webhook 一覧画面 Discord Webhook 設定画面

Discordのサーバーの設定もしくはチャンネルの設定画面で、左側のWebhooksからWebhookを作成します。このときに指定したチャンネルにメッセージが送信されます。

WordPressの設定

WordPressの管理画面のメニューから、外観→テーマの編集を開き、テーマのための関数(functions.php)を編集します。ファイルの末尾に次のコードを追記します。

  • テーマの編集を一度もしたことがない場合は警告画面が表示されます。よく読み、納得した上で次の手順に進んでください。心配な方はテーマの複製を行っておくことをおすすめします。
function post_discord($content, $embeds = null) {
	$jsonData = $embeds !== null ? json_encode(array('content' => $content, 'embeds' => $embeds)) : json_encode(array('content' => $content));
	$ch = curl_init('Webhook URL');
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
	curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	$res = curl_exec($ch);
	curl_close($ch);
	return $res;
}

function post_notify($new, $old, $post) {
	if ($new !== 'publish') return;
	switch ($old) {
		case 'new':
		case 'draft':
		case 'pending':
		case 'auto-draft':
		case 'future':
			post_discord('新規投稿', array(array('title' => get_the_title($post), 'url' => get_permalink($post), 'description' => get_the_excerpt($post), 'color' => 30719)));
	}
}

function update_notify($new,$old,$post) {
	if ($post -> post_status !== 'publish') return;
	post_discord('記事更新', array(array('title' => $post -> post_title, 'url' => get_permalink($post -> ID), 'description' => get_the_excerpt($post -> ID), 'color' => 30719)));
}

add_action('transition_post_status', 'post_notify', 10, 3);
add_action('post_updated', 'update_notify', 10, 3);

次回以降の記事投稿/更新時にDiscordにメッセージが送信されます。

Discord 表示例

その他

  • 記事投稿時にpost_notify関数、記事更新時にupdate_notify関数が実行されます
  • DiscordのEmbedsを使用しているため、記事のタイトルや抜粋が一緒に表示されます
  • 記事の抜粋は、記事に抜粋が入力されている場合のみ表示されます
  • 色指定は、16進数のカラーコードをRGBに分割せずにそのまま10進数に変換したものが使用できます(このコードでは#0077FF)。PHPを使用しているため、0x77ffでも大丈夫です

外部リンク

カテゴリ: WordPress