wp_after_insert_post()


WordPressのwp_after_insert_post()関数は、投稿や固定ページがデータベースに挿入された後に実行されるアクションです。この関数は、投稿の作成や更新後に追加の処理を実行するために使用されます。

構文

do_action( 'wp_after_insert_post', int $post_id, WP_Post $post, bool $update, ?WP_Post $post_before );

引数の説明:

  • $post_id(int) — 投稿ID
  • $post(WP_Post) — 投稿オブジェクト
  • $update(bool) — 更新か新規作成かを示すフラグ
  • $post_before(?WP_Post) — 更新前の投稿オブジェクト(更新時のみ)

例1: 投稿作成後にログを記録

投稿が作成されたときにログを記録します。

add_action('wp_after_insert_post','log_new_post');function log_new_post($post_id,$post,$update,$post_before){if(!$update){error_log('新規投稿作成:'.$post->post_title);}}

例2: 投稿更新時にメタデータを追加

投稿が更新されたときにカスタムメタデータを追加します。

add_action('wp_after_insert_post','add_post_meta_on_update');function add_post_meta_on_update($post_id,$post,$update,$post_before){if($update){update_post_meta($post_id,'last_updated',current_time('mysql'));}}

例3: 特定の投稿タイプのみ処理

カスタム投稿タイプ「product」のみを処理します。

add_action('wp_after_insert_post','handle_product_posts');function handle_product_posts($post_id,$post,$update,$post_before){if($post->post_type==='product'){//処理}}

例4: 投稿前後の内容を比較

投稿が更新された際に内容の変更をチェックします。

add_action('wp_after_insert_post','check_post_changes');function check_post_changes($post_id,$post,$update,$post_before){if($update&&$post_before->post_content!==$post->post_content){//内容変更時の処理}}

例5: 投稿ステータス変更時の処理

投稿ステータスが変更されたときに処理を実行します。

add_action('wp_after_insert_post','handle_status_change');function handle_status_change($post_id,$post,$update,$post_before){if($update&&$post_before->post_status!==$post->post_status){//ステータス変更時の処理}}

例6: 投稿作成後にデフォルトタグを追加

新規投稿にデフォルトタグを自動的に追加します。

add_action('wp_after_insert_post','add_default_tags');function add_default_tags($post_id,$post,$update,$post_before){if(!$update){wp_set_post_tags($post_id,'デフォルトタグ',true);}}

例7: 投稿更新後に通知メールを送信

投稿が更新された際に管理者に通知メールを送信します。

add_action('wp_after_insert_post','send_update_notification');function send_update_notification($post_id,$post,$update,$post_before){if($update){wp_mail(get_option('admin_email'),'投稿が更新されました','投稿ID:'.$post_id.'が更新されました');}}

注意点

  • このフックはデータベースへの挿入後に実行されますが、まだコミットされていない可能性があります。
  • 無限ループを避けるため、このフック内で同じ投稿を更新しないように注意してください。
  • パフォーマンスに影響する可能性があるため、重い処理は避けるか非同期で実行してください。