2021/04/28
Wordpress /
WPとGithub Actionsで自動デプロイ WordPressに設定編

投稿更新後github actionsに通知され、自動ビルドとデプロイを行う方法のwordpressの設定の方を紹介します。
curl使用方法はお決まりな感じではありますが、以下に記入しています。
urlやtokenはgithubの方で生成されますのでそちらを記入します。
wordpressのfunctions.phpに以下を追記
function post_save_wordpress($post_id, $post)
{
if ($post->post_status === 'publish') {
$url = 'https://api.github.com/repos/user/repo/dispatches'; // user/repoosは変更する必要があります。
$headers = [
'Authorization: bearer token',
'Accept: application/vnd.github.v3+json',
'User-Agent: post_save_wordpress'
];
$data = [
'event_type' => 'post_save_wordpress',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return true;
}
return false;
}
add_action('publish_post', 'post_save_wordpress', 10, 2);
add_action('delete_post', 'post_save_wordpress', 10, 2);
add_action('trashed_post', 'post_save_wordpress', 10, 2);
複数投稿箇所がある場合
add_action('publish_news', 'post_save_wordpress', 10, 2);
add_action('delete_new', 'post_save_wordpress', 10, 2);
add_action('trashed_news', 'post_save_wordpress', 10, 2);
add_action('publish_blog', 'post_save_wordpress', 10, 2);
add_action('delete_blog', 'post_save_wordpress', 10, 2);
add_action('trashed_blog', 'post_save_wordpress', 10, 2);
delete_***
投稿またはページが削除されようとする際に実行されます。
publish_***
投稿が公開された際や編集されてステータスが「公開済み」に変わった際に実行されます。
trashed_***
投稿またはページがゴミ箱に移動された後に実行されます。