function insert_chatgpt_comment_acf($post_id) {
// Check if the post is of type 'post'
if (get_post_type($post_id) != 'post') {
return;
}
// Check if there are rows in the field 'chatgpt_comments'
if (have_rows('chatgpt_comments', $post_id)) {
// Loop through the rows
while (have_rows('chatgpt_comments', $post_id)) {
the_row();
// Get the values of the sub-fields
$name = get_sub_field('name');
$email = get_sub_field('email');
$text = get_sub_field('comment_text');
$comment_id = get_sub_field('comment_id'); // Get the comment ID
$comment_date = get_sub_field('comment_date'); // Get the comment date
// Prepare the comment data
$data = array(
'comment_post_ID' => $post_id,
'comment_author' => $name,
'comment_author_email' => $email,
'comment_content' => $text,
'comment_type' => '',
'comment_parent' => 0,
'user_id' => 1,
'comment_author_IP' => '127.0.0.1',
'comment_agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
'comment_date' => $comment_date, // Use the chosen comment date
'comment_approved' => 1,
);
// If a comment ID is provided, update the existing comment
if ($comment_id) {
$data['comment_ID'] = $comment_id;
wp_update_comment($data);
} else {
// If the comment date is in the future, schedule the comment to be inserted at that time
if (strtotime($comment_date) > time()) {
wp_schedule_single_event(strtotime($comment_date), 'insert_chatgpt_comment', array($data));
} else {
// Otherwise, insert the comment immediately
$comment_id = wp_insert_comment($data);
// Update the 'comment_id' field with the ID of the new comment
update_sub_field('comment_id', $comment_id);
}
}
}
}
}
// Add the function to the 'acf/save_post' action so it is run when you publish or update a post
add_action('acf/save_post', 'insert_chatgpt_comment_acf', 20);
function insert_chatgpt_comment($data) {
// Insert the comment
$comment_id = wp_insert_comment($data);
// Update the 'comment_id' field with the ID of the new comment
update_sub_field('comment_id', $comment_id);
}
add_action('insert_chatgpt_comment', 'insert_chatgpt_comment', 10, 1);