Comments to Custom Post Type

时间:2016-06-01 作者:John Enxada

我正在切换到一个使用自定义帖子类型的新主题:问题(作为帖子)和答案(作为帖子的评论)。我使用插件将当前帖子转化为疑问。现在,我必须将(每个帖子的)评论转换为与每个(转换后的)问题相关的答案。

我使用了下面的代码,但尽管所有的评论都进行了转换,并与每个问题建立了正确的关系,但我最终得到了多个答案,这取决于每个帖子中的评论数量。更清楚地说,如果一个问题之前有5条评论,现在我有5x5=25个答案。代码实际上插入了5次答案,而不是1次。

我认为问题出在foreach循环中。你能帮我修改代码以避免这个问题吗?

$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;

1 个回复
最合适的回答,由SO网友:CK MacLeod 整理而成

Please try:

$args = array(
    \'posts_per_page\' => -1,
    \'post_type\' => \'thread\'
);

$thread_posts = get_posts( $args ); // Get all posts of thread.

foreach($thread_posts as $thread_post_object) {

    /*not sure really need to be working IDs only, but is simpler, plus made checking was getting right ones easier */
    $thread_post_IDs[] = $thread_post_object->ID; 

}

foreach ($thread_post_IDs as $thread_post_ID) {


    $comments_query = new WP_Comment_Query;
    $thread_comments = $comments_query->query(array 
        (
            \'post_id\' => $thread_post_ID,
            \'status\' => \'approve\'
        )
    );

    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_post_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 - requires registered users otherwise returns 0
            \'post_title\' => \'RE: \' . get_the_title($thread_post_ID), //since have ID only need alternative way to get title
            \'post_content\' => $thread_comment->comment_content // Set comment content as post content.
        );

        //print_r($reply_post); // if you want to test it first
        wp_insert_post($reply_post); // if you want to see what happens!

    }

}