Using the save_post Action Hook
Definition:
save_postfires after a post (any post type) is created or updated in the database.- Lets you run custom code (e.g., saving metadata, triggering notifications) whenever a post is saved.
Basic Example
function my_save_post_callback( $post_id, $post, $update ) {
// 1. Avoid running on autosave or revision
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( wp_is_post_revision( $post_id ) ) return;
// 2. Check user permissions
if ( ! current_user_can( 'edit_post', $post_id ) ) return;
// 3. Run your custom logic (e.g., save custom field)
if ( isset( $_POST['my_custom_field'] ) ) {
update_post_meta( $post_id, 'my_custom_field', sanitize_text_field( $_POST['my_custom_field'] ) );
}
}
add_action( 'save_post', 'my_save_post_callback', 10, 3 );Parameters
save_post passes 3 arguments:
$post_id→ The ID of the post being saved.$post→ The post object.$update→trueif updating an existing post,falseif creating a new one.
Best Practices
Always check for DOING_AUTOSAVE to avoid duplicate triggers.
Skip wp_is_post_revision() to avoid affecting post revisions.
Verify nonces for security if saving form data.
Use save_post_{post_type} for targeting specific post types.
Example:
add_action( 'save_post_product', 'my_product_save_callback', 10, 3 );💡 Analogy:
Hooking into save_post is like installing a camera in the kitchen — you get notified every time a new dish is made or updated, so you can take action right away.
