I'm switching to a new theme which uses the custom post types: Question (as posts) and Answer (as comments to posts). I have converted current Posts into Question using a plugin. Now, I have to convert comments (of each post) to Answer which will be relate to each (converted) Question.
I used the following code but although all comments converted and created the right relation to each question, I finally got multiple answer depending on how many comments where in each post. To be more clear, if a question had 5 comments before, now I have 5x5=25 answers. The code actually inserted the answers 5 times instead of just 1.
I think that the problem is in the foreach loop. Can you please help how should I modify the code to avoid this problem?
$args = array( 'posts_per_page' => -1, 'post_type' => 'thread' ); $threads= get_posts( $args ); // Get all posts of thread. foreach($threads as $thread): $comment_args= array( 'post_id' => $thread->ID ); $thread_comments= get_comments($comment_args); // Get all comments of the post. foreach($thread_comments as $thread_comment): $reply_post= array( 'post_status' => 'publish', // Set replies status. 'post_type' => 'answer', // Set post type, post type must be answer. 'post_parent' => $thread->ID // Set id of question to make relation between question and answer 'post_author' => $thread_comment->user_id, // Set comment user id as post id. 'post_title' => 'RE: '.$thread->post_title, //They prefix RE: to every reply so i think we might be do the same. 'post_content' => $thread_comment->comment_content // Set comment content as post content. ); wp_insert_post($reply_post); // Insert the comment as post having post type replies. endforeach; endforeach;