以下是您的代码的更新版本:
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);
}
...
}
以下是我所改变的:
传入post ID到save_post_type_example_meta_boxes
应该是您想用作“家长”帖子ID的内容。
您应该暂时删除挂钩save_post
这样它就不会一次又一次地执行该操作如@Milo所述,wp_insert_post
成功时返回一个帖子ID,这样就可以得到“child”帖子ID。