投稿に独自ステータスを追加する方法

Cocoonカスタマイズ集
この記事は約7分で読めます。
記事内に広告が含まれています。

はじめに

ネット検索すると、投稿に独自のステータスを追加する方法についていくつか掲載されています。
しかし、ほとんどの解説はクラシックエディターを対象としており、Gutenbergエディターでは対応していません。
Gutenbergエディターは内部構造がReactによるブロックエディターのため、クラシックエディターのように簡単にステータスを反映できません。

そこで、独自にステータス用のメタボックスを設けることで、クラシックエディターでも Gutenbergエディターでも投稿ステータスを追加できるようにします。

投稿ステータス「却下」を追加し、さらに、投稿ステータスが「却下」に変更された際には、投稿者に自動でメール通知が送信されるようにします。

この記事では、この方法について説明します。

完成イメージ

実装手順

以下のコードをfunctions.phpに追加します。

// 投稿ステータスを追加
add_action('init', function () {
  register_post_status('rejected', [
    'label'                     => '却下',
    'public'                    => false,
    'exclude_from_search'       => true,
    'show_in_admin_all_list'    => true,
    'show_in_admin_status_list' => true,
    'label_count'               => _n_noop('却下 (%s)', '却下 (%s)'),
  ]);
});


// メタボックスを追加
add_action('add_meta_boxes', function () {
  add_meta_box(
    'rejected_status',
    '投稿ステータス(拡張)',
    'render_rejected_status',
    'post',
    'side',
    'high'
  );
});


/**
 * メタボックスの入力フォームを出力
 *
 * @param WP_Post $post 投稿オブジェクト
 * @return void
 */
if (!function_exists('render_rejected_status')):
function render_rejected_status($post) {
  // 現在のステータスを取得
  $current_status = $post->post_status;

  wp_nonce_field('rejected_status_action', 'rejected_status_nonce');
  ?>
  <label for="rejected-status">ステータス:</label>
  <select name="rejected_status" id="rejected-status">
    <option value="publish"  <?php selected($current_status, 'publish'); ?>>公開</option>
    <option value="draft"    <?php selected($current_status, 'draft'); ?>>下書き</option>
    <option value="pending"  <?php selected($current_status, 'pending'); ?>>レビュー待ち</option>
    <option value="rejected" <?php selected($current_status, 'rejected'); ?>>却下</option>
  </select>
  <?php
}
endif;


// 投稿保存時にステータスを制御
add_filter('wp_insert_post_data', function ($data, $postarr) {
  // 許可するステータスを設定
  $allowed = ['publish', 'draft', 'pending', 'rejected'];

  if (!isset($_POST['rejected_status'])) {
    return $data;
  }

  // nonceチェック
  if (!isset($_POST['rejected_status_nonce']) || !wp_verify_nonce($_POST['rejected_status_nonce'], 'rejected_status_action')) {
    return $data;
  }

  // 権限チェック
  if (!current_user_can('edit_post', $postarr['ID'])) {
    return $data;
  }

  $new_status = sanitize_text_field($_POST['rejected_status']);

  // 許可されたステータスの場合のみ反映
  if (in_array($new_status, $allowed, true)) {
    $data['post_status'] = $new_status;
  }

  return $data;
}, 10, 2);


// 対象の処理を実行
add_action('admin_footer-edit.php', function () {
  ?>
  <script>
  jQuery(function ($) {
    const rejectedOption = '<option value="rejected"><?= esc_js('却下'); ?></option>';

    // クイック編集・一括編集のステータス選択欄を確認
    $('select[name="_status"], select[name="post_status"]').each(function () {
      // 「却下」が未登録の場合のみ追加
      if ($(this).find('option[value="rejected"]').length === 0) {
        $(this).append(rejectedOption);
      }
    });
  });
  </script>
  <?php
});


// 投稿ステータスが「却下」の場合に投稿者へメール通知
add_action('transition_post_status', function ($new_status, $old_status, $post) {
  // 投稿タイプとステータス変更の条件を確認
  if ($post->post_type !== 'post' || 'rejected' !== $new_status || $old_status === $new_status) {
    return;
  }

  // 投稿者のユーザー情報を取得
  $author = get_userdata($post->post_author);
  if (!$author || !$author->user_email) {
    return;
  }

  // メールの件名と本文を構築
  $subject = 'あなたの投稿が却下されました';
  $message = 'こんにちは ' . $author->display_name . " さん\n\n";
  $message .= '投稿「' . $post->post_title . "」は管理者により却下されました。\n\n";
  $message .= '投稿を確認する場合はこちら: ' . get_edit_post_link($post->ID) . "\n\n";
  $message .= 'よろしくお願いします。';

  // 投稿者へメールを送信
  wp_mail($author->user_email, $subject, $message);
}, 10, 3);

さいごに

今回紹介した方法を使えば、投稿ステータス「却下」などの独自ステータスを追加し、クラシックエディター・Gutenbergエディター両方で利用できます。
さらに、投稿が却下された際に投稿者へ自動でメール通知する仕組みも組み込めるため、多人数でのサイト運営において、承認・却下などのワークフローを構築することが可能です。
これにより、投稿管理の効率化と品質の担保を両立できます。

タイトルとURLをコピーしました