Skip to content

Instantly share code, notes, and snippets.

@styledev
Created October 10, 2018 22:34
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 styledev/4e98c7c5b4cb63ed75d83c5c1f6626b3 to your computer and use it in GitHub Desktop.
Save styledev/4e98c7c5b4cb63ed75d83c5c1f6626b3 to your computer and use it in GitHub Desktop.
A WordPress Action to sideload images into your site from the imported post content.
function action_pmxi_saved_post( $id ) {
$dir = wp_upload_dir();
$img_array = [];
$media = get_attached_media('image', $id);
$thepost = get_post($id);
foreach($media as $media_id => $item) {
$metadata = wp_get_attachment_metadata($item->ID, true);
$directory = explode('/', $metadata['file']);
$metadata['directory'] = "{$directory[0]}/{$directory[1]}";
foreach ($metadata['sizes'] as $size => $args) {
$img_array[$args['file']] = array(
'id' => $media_id,
'url' => "{$dir['baseurl']}/{$metadata['directory']}/{$args['file']}"
);
}
}
remove_all_filters('the_content');
$html = $thepost->post_content;
$doc = new DOMDocument();
@$doc->loadHTML($html);
$i = 0;
$imageTags = $doc->getElementsByTagName('img');
foreach($imageTags as $tag) {
$tag_url = $tag->getAttribute('src');
$classes = $tag->getAttribute('class');
foreach ($img_array as $filename => $args) {
if ( strpos($tag_url, $filename) ) {
$classes_new = preg_replace('/wp-image-[0-9]*/i', "wp-image-{$args['id']}", $classes);
$tag->setAttribute('class', $classes_new);
$tag->setAttribute('src', $args['url']);
continue;
}
}
}
$post_content = preg_replace(array('/<!DOCTYPE.*\n?<html><body><p>/', '/<\/p><\/body><\/html>/'), '', $doc->saveHTML());
$args = array('ID' => $id, 'post_content' => $post_content);
wp_update_post($args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment