I think one key question here is how _select_match_from_id
meta value is saved? Is it some metafield on the post edit screen or from some other logic?
If I may assume that it is from a metafield, then you could just read its value from the $_POST
array.
You could also improve your code by splitting the callback function into two, one for new posts and the other for updates, and moving the database action into a separate function.
Using the save_post_{$post->post_type}
helps you eliminate the post type check from the callback. The save_post
callback recieves also a third parameter bool $update
which you can use to determine, if it is a new post that is saved or an post update.
So you could for example do the following,
// Use post type specific actions to eliminate post type checking in callback
add_action('save_post_match', 'when_save_post_match', 10, 3);
add_action('save_post_match', 'when_update_post_match', 10, 3);
function when_save_post_match(int $post_id, WP_Post $post, bool $update) {
// only new posts
if ( $update ) {
return;
}
// get data for new post
$id_match = new_posts_match_from_db($post_id);
// pass id and data to action
execute_database_action($post_id, $id_match);
}
function new_posts_match_from_db(int $post_id) {
// this could be from the posted values as below or some other logic
// TODO: update to match your setup
return $_POST['_select_match_from_db'] ?? null;
}
function when_update_post_match(int $post_id, WP_Post $post, bool $update) {
// only updates
if ( ! $update ) {
return;
}
// get data from post meta
$id_match = existing_posts_match_from_db($post_id);
// pass id and data to action
execute_database_action( $post_id, $id_match );
}
function existing_posts_match_from_db(int $post_id) {
return get_post_meta( $post_id, '_select_match_from_db', true );
}
function execute_database_action(int $post_id, $id_match) {
// your db action...
}
Modify as needed.