投稿を特定カテゴリーで自動非公開と公開解除する方法

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

はじめに

特定の投稿を限定的に管理したい場合、通常は「公開状態」を手動で「非公開」に設定します。
しかし投稿数が多い場合、毎回手動で設定するのは手間がかかり、設定漏れによる意図せぬ公開のリスクもあります。

そこで、投稿に特定のカテゴリー(例:private)を付けるだけで、自動的に非公開に設定する仕組みを作ります。

さらに、カテゴリーを削除した場合に自動で公開状態に戻すことで、運用ミスを防ぐことも可能です。

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

自動で非公開にする方法

投稿保存時にカテゴリーprivateが付いている場合、自動で非公開に設定します。

実装手順

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

add_action('save_post', function ($post_id, $post, $update) {
  $target_category_slug = 'private'; // 非公開カテゴリー

  if ($post->post_type !== 'post') {
    return;
  }

  // 自動保存チェック
  if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
    return;
  }

  // リビジョンを除外
  if (wp_is_post_revision($post_id)) {
    return;
  }

  // 更新処理中は処理対象外
  static $is_updating = false;
  if ($is_updating) {
    return;
  }

  $has_category = has_category($target_category_slug, $post_id);
  $is_private   = ($post->post_status === 'private');

  // 状態が一致する場合は終了
  if (
    ($has_category && $is_private) ||
    (!$has_category && !$is_private)
  ) {
    return;
  }

  $is_updating = true;

  // 投稿ステータスを変更
  wp_update_post([
    'ID'          => $post_id,
    'post_status' => $has_category ? 'private' : 'publish',
  ]);

  $is_updating = false;
}, 10, 3);

カテゴリー削除時に非公開を自動解除する方法

上記の方法では、カテゴリーprivateを削除しても投稿は非公開のまま残ります。
しかし、運用上はカテゴリー削除と同時に非公開を解除し、公開状態に戻したい場合があります。
そこで、カテゴリーを削除した際に、投稿のステータスを自動で公開に変更します。

実装手順

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

add_action('pre_delete_term', function ($term_id, $taxonomy) {
  $target_category_slug = 'private';

  if ($taxonomy !== 'category') {
    return;
  }

  // 対象カテゴリー以外は処理対象外
  $term = get_term($term_id, $taxonomy);
  if (!$term || $term->slug !== $target_category_slug) {
    return;
  }

  // 対象カテゴリーの投稿IDを取得
  $posts = get_posts([
    'post_type'      => 'post',
    'posts_per_page' => -1,
    'tax_query'      => [
      [
        'taxonomy' => 'category',
        'field'    => 'term_id',
        'terms'    => $term_id,
      ],
    ],
    'fields'         => 'ids',
  ]);

  // 投稿なしは処理対象外
  if (empty($posts)) {
    return;
  }

  // カテゴリー削除後に投稿ステータスを公開に変更
  add_action('delete_term', function ($deleted_term_id, $deleted_tt_id, $deleted_taxonomy) use ($posts, $term_id) {
    // 対象カテゴリー以外は処理対象外
    if ($deleted_taxonomy !== 'category' || $deleted_term_id !== $term_id) {
      return;
    }

    global $wpdb;

    // 投稿ステータスを一括更新
    $post_ids_placeholder = implode(',', array_fill(0, count($posts), '%d'));
    $query = $wpdb->prepare(
      "UPDATE {$wpdb->posts} SET post_status = 'publish' WHERE ID IN ({$post_ids_placeholder}) AND post_type = 'post'",
      ...$posts
    );

    $wpdb->query($query);
  }, 10, 3);
}, 10, 2);

さいごに

今回紹介した方法を使えば、投稿に特定カテゴリーを設定するだけで自動的に非公開に設定され、手動設定ミスによる公開の漏れを防ぐことができます。
また、カテゴリーを削除した場合には自動で公開状態に戻るため、非公開運用の管理を安全かつ効率的に行うことが可能です。

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