I’ve just been writing a WordPress plugin that adds various fields to the Manage > Page screen in the dashboard, and then saves the contents to a custom database table when the page is saved. Strangely, I found that everything in the fields added by the plugin was being written to the database twice.
The function that saves the contents of the fields is hooked into the save_post action. The save_post action, it turns out, is called twice when a page is saved.
To prevent duplicate entries when using save_post in this way, you need to make sure that no matter how many times the function hooked into save_post is called, it only runs once. Something like this should do it:
add_action('save_post', 'save_function');
function save_function {
global $flag;
if ($flag == 0) {
// do stuff
}
$flag = 1;
}
Even if you aren’t writing new rows to a database, it’s good to be aware that anything hooked into save_post will be called twice, and probably a good idea to make sure that it only executes in full once.