wp_transition_post_status()


WordPressのwp_transition_post_status()関数は、投稿のステータスが変更されたときに実行されるアクションを定義するために使用されます。

シンタックス

wp_transition_post_status( string $new_status, string $old_status, WP_Post $post );

引数の説明

  • $new_status (string) — 新しい投稿ステータス。
  • $old_status (string) — 変更前の投稿ステータス。
  • $post (WP_Post) — 投稿オブジェクト。

例 1: 投稿ステータス変更時のメッセージ表示

以下のコードは、投稿ステータスが変更された際に管理画面にメッセージを表示します。

add_action( 'transition_post_status', 'custom_post_status_transition', 10, 3 );

function custom_post_status_transition( $new_status, $old_status, $post ) {
    if ( 'publish' === $new_status && 'draft' === $old_status ) {
        echo '<div class="notice notice-success">投稿が公開されました。</div>';
    }
}

例 2: 投稿ステータス変更時のログ出力

ステータス変更時にファイルへログを書き込みます。

add_action( 'transition_post_status', 'log_post_status_change', 10, 3 );

function log_post_status_change( $new_status, $old_status, $post ) {
    error_log( "投稿ID {$post->ID} のステータスが '{$old_status}' から '{$new_status}' に変更されました。" );
}

例 3: ステータス変更時のメール通知

投稿が「公開」ステータスに変更された際、メール通知を送信します。

add_action( 'transition_post_status', 'send_email_on_publish', 10, 3 );

function send_email_on_publish( $new_status, $old_status, $post ) {
    if ( 'publish' === $new_status && 'publish' !== $old_status ) {
        wp_mail( 'admin@example.com', '新しい投稿が公開されました', "投稿ID: {$post->ID} が公開されました。" );
    }
}

例 4: カスタム投稿タイプに限定した処理

カスタム投稿タイプのみステータス変更時に処理を実行します。

add_action( 'transition_post_status', 'handle_custom_post_status', 10, 3 );

function handle_custom_post_status( $new_status, $old_status, $post ) {
    if ( 'my_custom_post_type' === $post->post_type && 'publish' === $new_status ) {
        // カスタム投稿タイプの追加処理
    }
}

例 5: ステータス変更時の条件分岐

複数の条件に応じて異なる処理を実行します。

add_action( 'transition_post_status', 'conditional_post_status_actions', 10, 3 );

function conditional_post_status_actions( $new_status, $old_status, $post ) {
    if ( 'publish' === $new_status ) {
        // 公開時の処理
    } elseif ( 'trash' === $new_status ) {
        // ゴミ箱移動時の処理
    }
}

注意事項

  • wp_transition_post_status()は、ステータス変更時に自動で呼び出される関数です。手動で呼び出す必要はありません。
  • フックを使用する際、適切な条件分岐を設定して不要な処理を避けてください。

関連機能: