Wednesday, December 16, 2009

WordPress CLI Import

So a few weeks back I wrote some code to export a WordPress blog via the command line. Now, to come full circle I finished dissecting the code to import a WordPress blog via CLI.

Now before proceding, I highly recommend going through the import/export process via the admin GUI if you have not done so already. Doing so will let you understand fully what the entire process is like and can see why some parts of code were written.

At this point I assume that an xml export has already been made; if not, go make one!

Here's the entire code:

if ($argc < 4) {
print "Usage: $argv[0] from_topic to_topic xml_file\n";
exit;
}


$user_login = $argv[2];
include 'wp-config.php';
include 'wp-admin/includes/import.php';
include 'wp-includes/registration.php';
include 'wp-admin/includes/post.php';
include 'wp-admin/includes/taxonomy.php';
include 'wp-admin/import/wordpress.php';

// the WP_Import class looks for POST values for author_in and user_select
// author_in is an array of users to import
$_POST['author_in'][1] = $argv[1];

// user_select is an array of the selected user's ID for posts to be mapped to
// if empty, the user in author_in will be created
$userdata = get_userdatabylogin( $user_login );
$_POST['user_select'][1] = $userdata->ID;

$wp_import = new WP_Import();
$wp_import->import_file($argv[3]);


The code is short and simple. The only part that was hard to understand was how the author_in and user_select POST arrays were used so, I'm going to take a minute to give a brief explanation.

$_POST['author_in'][1] = $argv[1];

Right now, I only have a need to import a 1-to-1 user mapping; meaning: import one user's posts and map them to an existing user. Though of course, with a little more work, this code can support a multiple user import.

The author_in array is a 0...n key array where the values are the users to-be-imported. Remember though, you'll need to remember what key you use since it'll be the same key for the user_select array.


$userdata = get_userdatabylogin( $user_login );
$_POST['user_select'][1] = $userdata->ID;


Now, the user_select array is made up of the existing blog's user's IDs where the key is the same key for whatever was used for the author_in array. (Yes, this is what confused me!)

If you wanted to import multiple users' blogs you'll understand these two arrays better.

Example
Users to be imported: jim, mary
To be mapped to these users: frank, sue (respectively)

Now the arrays would look something like this:

$_POST['author_in'][0] = 'jim';
$_POST['author_in'][1] = 'mary';

$userdata = get_userdatabylogin( 'frank' );
$_POST['user_select'][0] = $userdata->ID;
$userdata = get_userdatabylogin( 'sue' );
$_POST['user_select'][1] = $userdata->ID;


Now hopefully you'll see what's going on now if you look at the array keys!

Enjoy! Cheers!

No comments: