wp_insert_post
云策文档标注
概述
wp_insert_post 是一个 WordPress 动作钩子,在文章保存后触发,可用于执行自定义逻辑。它区分新文章和更新操作,并支持在管理界面或通过 wp_insert_post() 函数调用时触发。
关键要点
- 触发时机:文章保存后立即触发,适用于新文章创建或现有文章更新。
- 参数:$post_id(文章ID)、$post(文章对象)、$update(是否为更新操作)。
- 与 save_post 的区别:wp_insert_post 在 update_post_meta 之后触发,且可通过条件排除特定状态。
- 使用场景:常用于发送通知、日志记录或数据同步等后处理任务。
代码示例
function my_project_updated_send_email( $post_id, $post, $update ) {
// 如果是修订版本,不发送邮件
if ( wp_is_post_revision( $post_id ) )
return;
$post_url = get_permalink( $post_id );
$subject = 'A post has been updated';
$message = "A post has been updated on your website:nn";
$message .= $post->post_title . ": " . $post_url;
// 发送邮件给管理员
wp_mail( 'admin@example.com', $subject, $message );
}
add_action( 'wp_insert_post', 'my_project_updated_send_email', 10, 3 );注意事项
- 在仪表板中首次发布文章时,$update 可能为 true,因为系统会创建修订版本,需谨慎处理首次发布检测。
- 避免在钩子中执行耗时操作,以防影响保存性能。
原文内容
Fires once a post has been saved.
Parameters
$post_idint-
Post ID.
$postWP_Post-
Post object.
$updatebool-
Whether this is an existing post being updated.
Source
do_action( 'wp_insert_post', $post_id, $post, $update );
Changelog
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |
Skip to note 3 content
leogermani
Below is a basic example that will send an email every time a post or page is created or updated on your website. (copied from codex)
function my_project_updated_send_email( $post_id, $post, $update ) { // If this is a revision, don't send the email. if ( wp_is_post_revision( $post_id ) ) return; $post_url = get_permalink( $post_id ); $subject = 'A post has been updated'; $message = "A post has been updated on your website:nn"; $message .= $post->post_title . ": " . $post_url; // Send email to admin. wp_mail( 'admin@example.com', $subject, $message ); } add_action( 'wp_insert_post', 'my_project_updated_send_email', 10, 3 );Skip to note 4 content
Mário Valney
It’s not reliable to check first publication.
$updatewill betruein first time post is published if you are using dashboard because it creates revisions.