How to customize save function event?

WordPress fires a number of different hooks when a post is (published / updated / saved). It’s usually best to browse through the Codex to determine which hook fires when, and only when, you want to run your custom code. It’s important to be aware that some of these hooks fire multiple times when you click a single button.

In most cases you can’t run a var_dump(), so it’s often helpful to add a test function on each hook, and in that test function, fwrite to a log file including the timestamp and which hook ran. That way you can see the order of things and also how many times each hook ran, and start narrowing down a single place to run your custom code.

One hook you might want to explore: save_post. This hook gives you access to the post ID, the full WP $post object, and a boolean for whether this is an existing post being updated.

So, to test out the save_post hook, you could start with something like

add_action('save_post', 'wpse_see_save_post', 20, 3);
function wpse_see_save_post($post_id, $post, $update) {
    // Open a log file and add to it ("a")
    $file = fopen(__DIR__.'/save-post-hook.log', 'a');
    // Get the current timestamp
    $time = date("Y-m-d h:m");
    // Write timestamp and message to file
    fwrite($file, "$time - save_post ran");
    fclose($file);
}

You might also want to log a few other hooks such as transition_post_status and post_updated – maybe even to the same logfile so you see the full order of things and what’s available.

Once you know what order things are happening in, you can start accessing the data. For example:

add_action('save_post', 'wpse_see_save_post_data', 20, 3);
function wpse_see_save_post_data($post_id, $post, $update) {
    // Open a log file and add to it ("a")
    $file = fopen(__DIR__.'/save-post-data.log', 'a');
    // Get the current timestamp
    $time = date("Y-m-d h:m");
    // Write timestamp and message to file
    fwrite($file, "$time - save_post data includes\r\n");
    // access global $_POST array
    global $_POST;
    fwrite($file, print_r($_POST, true));
    fclose($file);
}

You’ll likely notice that the $_POST data is empty on one run, but populated on another. So, you can add a conditional in your function like

if(count($_POST) > 0) {

to have your custom code only run when you know you have access to the data you need.