Last active
August 29, 2015 13:55
-
-
Save vmassuchetto/8784430 to your computer and use it in GitHub Desktop.
WordPress migration template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// we need memory and time | |
ini set( 'memory limit', -1); | |
set_time_limit( 0 ); | |
// WordPress environment | |
include( 'wp-load.php' ); | |
// database to import posts from | |
global $wpdb; | |
$external_db = new wpdb( IMPORT_USER, IMPORT_PASS, IMPORT_DB, IMPORT_SERVER ); | |
foreach ( $external_db->get_results("<POSTS QUERY HERE>") as $p ) { | |
// insert a post | |
$args = array( | |
'post_title' => $p->title_column, | |
'post_content' => $p->content_column, | |
/* other database fields that match posts's columns */ | |
); | |
$post_id = wp_insert_post( $args ); | |
// parsing the post content for images | |
$content = $p->content_column; | |
$doc = new DOMDocument(); | |
@$doc->loadHTML($content); | |
$tags = $doc->getElementsByTagName('img'); | |
// import images as attachments | |
foreach ($tags as $tag) { | |
$url = echo $tag->getAttribute('src'); | |
$image_id = media_sideload_image($url, $post_id); | |
// update post URLs | |
$image_url = wp_get_attachment_image_src($image_id); | |
$content = str_replace($url, $image_url, $content); | |
} | |
// update post content | |
$args['ID'] = $post_id; | |
$args['post_content'] = $content; | |
wp_update_post($args); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment