钩子文档

wp_after_insert_post

💡 云策文档标注

概述

wp_after_insert_post 是一个 WordPress 动作钩子,在文章及其术语和元数据保存后触发。它允许开发者在文章插入或更新后执行自定义操作。

关键要点

  • 触发时机:文章、术语和元数据保存完成后立即触发。
  • 参数:包括 $post_id(文章ID)、$post(文章对象)、$update(是否为更新操作)、$post_before(更新前的文章对象或 null)。
  • 用途:常用于文章保存后的后续处理,如日志记录、缓存清理或触发其他事件。
  • 版本:从 WordPress 5.6.0 开始引入。

代码示例

add_action( 'wp_after_insert_post', 'my_custom_function', 10, 4 );
function my_custom_function( $post_id, $post, $update, $post_before ) {
    // 在此处添加自定义逻辑,例如:
    if ( $update ) {
        // 更新文章时的处理
        error_log( '文章已更新: ' . $post_id );
    } else {
        // 新文章插入时的处理
        error_log( '新文章已插入: ' . $post_id );
    }
}

注意事项

  • 确保回调函数正确处理所有参数,避免因参数缺失导致错误。
  • 此钩子触发时文章已保存,避免在此处修改文章内容以防止无限循环。
  • 参考 wp-includes/post.php 中的 wp_after_insert_post() 函数以了解内部实现。

📄 原文内容

Fires once a post, its terms and meta data has been saved.

Parameters

$post_idint
Post ID.
$postWP_Post
Post object.
$updatebool
Whether this is an existing post being updated.
$post_beforenull|WP_Post
Null for new posts, the WP_Post object prior to the update for updated posts.

Source

do_action( 'wp_after_insert_post', $post_id, $post, $update, $post_before );

Changelog

Version Description
5.6.0 Introduced.