Last active
January 14, 2018 00:29
-
-
Save mbissett/276dffed1de57b523c8b7ebd0967676a to your computer and use it in GitHub Desktop.
Update embedded images in imported post content
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 | |
// Hat tip to Trey Mills for the original code inspiration | |
add_action('pmxi_saved_post', 'update_images_in_post_content', 10, 3); | |
function update_images_in_post_content($id) { | |
$media = get_attached_media( 'image', $id ); | |
$img_array = []; | |
foreach($media as $item) { | |
$img_array[] = wp_get_attachment_url($item->ID); | |
} | |
$thepost = get_post($id); | |
remove_all_filters('the_content'); | |
$html = $thepost->post_content; | |
$doc = new DOMDocument(); | |
@$doc->loadHTML( $html ); | |
$imageTags = $doc->getElementsByTagName( 'img' ); | |
$i = 0; | |
foreach( $imageTags as $tag ) { | |
$tag->setAttribute( 'src', $img_array[$i] ); | |
$i++; | |
} | |
$newhtml = preg_replace(array('/<!DOCTYPE.*\n?<html><body><p>/', '/<\/p><\/body><\/html>/'), '', $doc->saveHTML()); | |
$args = array( | |
'ID' => $id, | |
'post_content' => $newhtml, | |
); | |
wp_update_post( $args ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is modified code if you do not want to worry about the order of the photos being sideloaded needing to match the order in which they appear in the content and also matching the sizes.
`
public function action_pmxi_saved_post($id) {
$media = get_attached_media( 'image', $id );
$img_array = [];
$dir = wp_upload_dir();
foreach($media as $media_id => $item) {
$metadata = wp_get_attachment_metadata($item->ID, true);
$directory = explode('/', $metadata['file']);
$metadata['directory'] = "{$directory[0]}/{$directory[1]}";
}
$thepost = get_post($id);
remove_all_filters('the_content');
$html = $thepost->post_content;
$doc = new DOMDocument();
@$doc->loadHTML( $html );
$imageTags = $doc->getElementsByTagName( 'img' );
$i = 0;
foreach( $imageTags as $tag ) {
$tag_url = $tag->getAttribute('src');
$classes = $tag->getAttribute('class');
}
$newhtml = preg_replace(array('/<!DOCTYPE.*\n?
/', '/</p></body></html>/'), '', $doc->saveHTML());
$args = array(
'ID' => $id,
'post_content' => $newhtml,
);
wp_update_post( $args );
}
`