LoginSignup
6
10

More than 5 years have passed since last update.

WordPressで記事が公開されたタイミングで処理をする

Last updated at Posted at 2017-10-25

経緯

とあるアプリでWordPressのコーポレートサイトの記事が公開されたら、アプリ通知を実行したいという要望があった。
その際に、「save_postにホックすれば余裕でしょ!」とか思ってたら痛い目を見たので、ここにメモ残しておきまする:pen_ballpoint:

ちなみにこの要望はのちになくなったのでこのソースコードは使われないことに....
供養も含めてメモメモ:disappointed_relieved::pray:

/**************************************
/* 公開された際の通知処理
/* 以下の順で実施。(ステータスが公開に変わったか)->(カスタムフィールドを取得し、何かしらの処理を実行)
/* transition_post_status(is_published_now)=>wp_insert_post(do_something_on_published)
**************************************/
function is_published_now($new_status, $old_status, $post){
  // 投稿のステータスが「新規追加」または「下書き保存」または「レビュー待ち」または「予約投稿」から
  // 「公開」へ変わった際にflgを立てておく(save_postやedit_post/wp_insert_post ではステータスの変化がわからないため)
  global $is_publiched;
  if (($old_status == 'auto-draft'  || $old_status == 'draft'
       || $old_status == 'pending'  || $old_status == 'future')
    && $new_status == 'publish' && $post->post_type == 'post') {

      if (empty($is_publiched) && $old_status == 'future')
      { // 予約投稿の際、wp_insert_postは呼び出されないので、ここで呼ぶ
        hoge($post);
      }
      else{
        $is_publiched = true;
      }
  }
  else {
    if (!$is_publiched) $is_publiched = false;
  }
}
add_action('transition_post_status', 'is_published_now', 10, 3);

// 投稿に変更があり、かつ公開ステータスとなった際に実行
// (カスタム項目が取得できない関係上、transition_post_statusでは処理ができない為wp_insert_postを利用する。(save_post/edit_postも不可))
function do_something_on_published($post_ID, $post){
  global $is_publiched;
  if ($is_publiched){
    hoge($post);
    $is_publiched = false;
  }
}
add_action('wp_insert_post', 'do_something_on_published', 100, 2);

function hoge($post){
 //ここに記事が公開されタイミングでしたい処理を描く。
}

参考サイト様。
感謝:
https://routecompass.net/twitter/

6
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
10