On Github xmattus / 2015-wcsea
Matt Johnson / @xmatt / alleyinteractive.com
We're gonna talk about code!
In functions.php for your theme:
if ( defined( 'WP_CLI' ) ) { require_once( MY_THEME_DIR . '/inc/class-migration-cli.php' ); }
In class-migration-cli.php:
class Migration_CLI extends WP_CLI_Command { public function fix_my_data( $args, $assoc_args ) { $per_page = 100; $page = 0; do { $posts = get_posts( array( ... // Your WP_Query arguments here. 'posts_per_page' => $per_page, 'offset' => $per_page * $page++, ) ); foreach ( $posts as $post ) { // Do your stuff here. wp_update_post( $post ); } } while ( $per_page == count( $posts ) ); } } WP_CLI::add_command( 'migration', 'Migration_CLI' );
Then run it on your server, local dev, or what have you:
$ cd /var/www/my_wp_site.com $ wp migration fix_my_data
Returning to class-migration-cli.php:
class Migration_CLI extends WP_CLI_Command { public function migrate_data( $args, $assoc_args ) { $this->connect_to_legacy_source(); while ( $this->has_legacy_data() ) { // Extract: $row = $this->get_legacy_post(); $post = array( 'post_type' => 'post', 'post_title' => $row['title'], 'post_content' => $row['content'], 'post_date' => date( 'Y-m-d H:i:s', strtotime( $row['date' ] ) ), ) // Transform: if ( $row['is_slideshow'] ) { $post['post_type'] = 'slideshow'; } // Load: $post_id = wp_insert_post( $post ); update_post_meta( $post_id, 'legacy_id', $row['id'] ); if ( $row['is_slideshow'] ) { update_post_meta( $post_id, 'slides', $this->get_legacy_slides( $row['id'] ) ); } } } } WP_CLI::add_command( 'migration', 'Migration_CLI' );
This line:
update_post_meta( $post_id, 'legacy_id', $row['id'] );means we can identify this post next time we run the script:
if ( $post_id = $this->new_post_exists( $row['id'] ) ) { $post['ID'] = $post_id; wp_update_post( $post ); } else { $post_id = wp_insert_post( $post ); }..and not have to wipe our our WP site each time we test the migration.
Want to do cool stuff like this?We're hiring.
info@alleyinteractive.com