Here’s an updated version of your code:
add_action('save_post', array($this, 'save_post_type_example_meta_boxes'));
function save_post_type_example_meta_boxes($post_id)
..........
if (...) {
$new_custom_post = array(
'post_title' => $title,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'custom_post_type',
'meta_input' => array(
'meta_1' => 'X',
'parent_post_id' => $post_id,
),
);
// Prevent this action from running twice.
remove_action( 'save_post', [ $this, 'save_post_type_example_meta_boxes' ] );
$child_post_id = wp_insert_post( $new_custom_post );
// Readd the action.
add_action('save_post', array($this, 'save_post_type_example_meta_boxes'));
}
update_post_meta($post_id, 'child_post_id', $child_post_id);
......
if(isset($_POST['meta_x_post'])) {
$meta_x = sanitize_text_field($_POST['meta_x_post']);
update_post_meta($post_id, 'meta_x', $meta_x);
}
...
}
And here’s what I changed:
- The incoming post ID to
save_post_type_example_meta_boxes
should be what you want to use as your “parent” post ID. - You should temporarily remove your hook to
save_post
so that it doesn’t try to run on that action over and over again. - As noted by @Milo,
wp_insert_post
returns a post ID on success, so that would give you the “child” post ID.