函数文档

wp_after_insert_post()

💡 云策文档标注

概述

wp_after_insert_post() 是一个 WordPress 函数,用于在文章、其分类项和元数据保存后触发动作。它主要作为 do_action 的包装器,提供参数处理并调用同名 Hook。

关键要点

  • 函数作用:在文章及其相关数据保存后执行动作,适用于新文章创建或现有文章更新场景。
  • 参数说明:接受三个参数:$post(文章 ID 或对象,必需)、$update(是否为更新操作,必需)、$post_before(更新前的文章对象,新文章时为 null,必需)。
  • 内部处理:函数首先通过 get_post() 获取文章对象,如果无效则返回;然后使用 do_action 触发 'wp_after_insert_post' Hook,传递处理后的参数。
  • Hook 信息:关联的 Hook 为 'wp_after_insert_post',传递参数 $post_id、$post、$update、$post_before,用于扩展文章保存后的自定义逻辑。
  • 版本历史:自 WordPress 5.6.0 版本引入。
  • 相关函数:与 do_action() 和 get_post() 紧密相关,并被多个 REST API 控制器和核心函数(如 wp_insert_post、wp_publish_post)使用。

注意事项

  • 注意参数顺序:函数定义和 Hook 调用时参数顺序一致,但文档中用户笔记提到访问 $post_before 属性时需注意参数数量(共4个参数)。
  • 区分函数和 Hook:此文档针对函数 wp_after_insert_post(),而非同名 Hook;Hook 的文档需参考其他页面。

📄 原文内容

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

Parameters

$postint|WP_Postrequired
The post ID or object that has been saved.
$updateboolrequired
Whether this is an existing post being updated.
$post_beforenull|WP_Postrequired
Null for new posts, the WP_Post object prior to the update for updated posts.

Source

function wp_after_insert_post( $post, $update, $post_before ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return;
	}

	$post_id = $post->ID;

	/**
	 * Fires once a post, its terms and meta data has been saved.
	 *
	 * @since 5.6.0
	 *
	 * @param int          $post_id     Post ID.
	 * @param WP_Post      $post        Post object.
	 * @param bool         $update      Whether this is an existing post being updated.
	 * @param null|WP_Post $post_before Null for new posts, the WP_Post object prior
	 *                                  to the update for updated posts.
	 */
	do_action( 'wp_after_insert_post', $post_id, $post, $update, $post_before );
}

Hooks

do_action( ‘wp_after_insert_post’, int $post_id, WP_Post $post, bool $update, null|WP_Post $post_before )

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

Changelog

Version Description
5.6.0 Introduced.

User Contributed Notes