How to get the `comment_post_ID`?

Do you actually insert the comments right after you created the CPT post?

I.e. Both the snippets in the question are in the same scope, e.g. wp_insert_post( $post_array ); for($j = 1; $j <= $total; $j++){ ... wp_insert_comment($comment_array); ... }.

If yes, then you can store the post ID returned by wp_insert_post() to a variable and then just use that variable with the comment_post_ID in your comment’s arguments. E.g.

$post_id = wp_insert_post( $post_array );

And then in the $comment_array, just use 'comment_post_ID' => $post_id.


But if the snippets run in different PHP session/execution, and if the post meta named ticket_id is unique for each post in your CPT, then you can use the WordPress meta query and get_posts() to get the post that references the original email.

So for example,

$posts = get_posts( array(
    'post_type'  => 'faqpress-tickets',
    'meta_key'   => 'ticket_id',
    'meta_value' => $mail['header']->message_id,
) );

if ( ! empty( $posts ) ) {
    $comment_array = array(
        'comment_content' => $mail['body'],
        'comment_post_ID' => $posts[0]->ID,
    );

    wp_insert_comment( $comment_array );
}

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)