save_post动作下重复值保存问题:每次保存产品数组被重复添加两次
save_post Hook Hey there! I totally get the frustration of having your array get duplicated every time you save a product—this is a super common pitfall with WordPress's save_post action, so you’re not alone here. Let’s break down why this happens and how to fix it.
Common Causes of Duplication
The most frequent culprit is that the save_post hook runs twice during a single save operation:
- Once for the automatic draft/autosave that WordPress creates in the background
- Again when you click the "Save" button to finalize the post/product
Other less common reasons include:
- Accidentally registering the
save_postaction multiple times in your code - Conflicts with other plugins/themes that also trigger
save_postfor the product
Step-by-Step Fix
Here’s how to adjust your code to prevent duplicate entries:
1. Skip Autosaves and Revisions
First, add checks to bypass the hook when WordPress is saving an autosave or post revision. This will stop the duplicate trigger from the background save.
2. Verify Post Type and User Permissions
Make sure you’re only running your code for product posts (if you’re using WooCommerce) and that the current user has permission to edit the product—this avoids unintended runs from other post types or unauthorised actions.
Example Fixed Code
add_action('save_post', 'add_product_to_array'); function add_product_to_array($post_id) { // Skip autosaves and revisions if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) { return; } // Only run for WooCommerce products if (get_post_type($post_id) !== 'product') { return; } // Ensure the user can edit this product if (!current_user_can('edit_post', $post_id)) { return; } // Your array handling logic // Get existing array from post meta (adjust the meta key to yours) $existing_array = get_post_meta($post_id, 'your_custom_array_key', true); // Initialize as empty array if it doesn't exist yet if (!is_array($existing_array)) { $existing_array = []; } // Add your new array entry (customize this to your needs) $new_entry = [ 'product_id' => $post_id, 'saved_at' => current_time('mysql'), // Add other data you need here ]; // Append the new entry to the existing array $existing_array[] = $new_entry; // Update the post meta with the updated array update_post_meta($post_id, 'your_custom_array_key', $existing_array); }
Additional Checks
If you’re still seeing duplicates after adding these checks:
- Double-check your code to make sure you’re not calling
add_action('save_post', ...)more than once - Temporarily deactivate other plugins to rule out conflicts (especially WooCommerce extensions)
- Check if your theme has any custom
save_posthooks that might be interfering
内容的提问来源于stack exchange,提问作者Ali

