Skip to content

Instantly share code, notes, and snippets.

@billerickson
Last active November 29, 2017 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save billerickson/88d897d62cce2aa6d50587ebe46e4517 to your computer and use it in GitHub Desktop.
Save billerickson/88d897d62cce2aa6d50587ebe46e4517 to your computer and use it in GitHub Desktop.
<?php
/**
* Comments Migration
*
*/
function ea_comments_migration() {
$site_url = 'https://yoursite.com';
$username = 'your_username';
$password = 'your_password';
$query_args = array(
'per_page' => 20,
'context' => 'edit',
);
$request_args = array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ),
),
);
$url = add_query_arg( $query_args, trailingslashit( $site_url ) . 'wp-json/wp/v2/comments' );
$response = wp_remote_get( $url, $request_args );
if( '200' != wp_remote_retrieve_response_code( $response ) )
return;
$comments = json_decode( wp_remote_retrieve_body( $response ) );
if( empty( $comments ) )
return;
// Reverse them so we start with oldest first
$comments = array_reverse( $comments );
// Save Old/New IDs for parent linking
$comment_ids = array();
foreach( $comments as $comment ) {
// Skip if comment exists
$existing = get_comment( $comment->id );
if( !empty( $existing ) && ! is_wp_error( $existing ) )
continue;
$parent = !empty( $comment->parent ) && array_key_exists( $comment->parent, $comment_ids ) ? $comment_ids[ $comment->parent ] : $comment->parent;
$commentdata = array(
'comment_post_ID' => $comment->post,
'comment_author' => $comment->author_name,
'comment_author_email' => $comment->author_email,
'comment_author_url' => $comment->author_url,
'comment_content' => $comment->content->raw,
'comment_type' => '',
'comment_parent' => $parent,
'user_id' => $comment->author
);
$id = wp_new_comment( $commentdata, true );
if( ! is_wp_error( $id ) )
$comment_ids[ $comment->id ] = $id;
}
}
//add_action( 'init', 'ea_comments_migration' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment