What is save_post Hook in WordPress: Explanation and Example
save_post hook in WordPress is an action triggered whenever a post or custom post type is saved or updated. It allows developers to run custom code right after WordPress saves post data, such as modifying metadata or validating input.How It Works
The save_post hook acts like a notification system that tells WordPress developers, "Hey, a post was just saved!" Imagine you have a notebook where you write notes, and every time you finish writing a page, a friend taps you on the shoulder to remind you to check something. This hook is that tap.
When you create or update a post, WordPress saves the content to the database. Right after this save action, it triggers the save_post hook, passing the post ID and other details. Developers can attach their own functions to this hook to perform extra tasks like saving custom fields, sending notifications, or cleaning up data.
Example
This example shows how to use the save_post hook to save a custom field called "subtitle" when a post is saved.
<?php function save_post_subtitle( $post_id ) { // Check if our custom field is set if ( isset( $_POST['subtitle'] ) ) { // Sanitize the input to keep it safe $subtitle = sanitize_text_field( $_POST['subtitle'] ); // Update the post meta with the subtitle update_post_meta( $post_id, '_subtitle', $subtitle ); } } add_action( 'save_post', 'save_post_subtitle' );
When to Use
Use the save_post hook when you want to run code right after a post is saved or updated. This is useful for:
- Saving custom fields or metadata entered by users.
- Validating or sanitizing post data before it is stored.
- Triggering actions like sending emails or clearing caches after content changes.
- Integrating with other plugins or external services when content updates.
For example, if you add extra information to posts via custom fields, you can use this hook to save that data safely every time the post is saved.
Key Points
- Triggered after post save: Runs immediately after WordPress saves a post.
- Receives post ID: Your function gets the post ID to work with.
- Use for custom data: Ideal for saving or updating custom fields.
- Sanitize inputs: Always clean user input before saving.
- Works for all post types: Applies to posts, pages, and custom post types.