Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save trey8611/a30ed000f6ef7dd45f7ab4c7c2a013a3 to your computer and use it in GitHub Desktop.
Save trey8611/a30ed000f6ef7dd45f7ab4c7c2a013a3 to your computer and use it in GitHub Desktop.
<?php
// Update image asset IDs after migrating using WP All Import Pro.
// Use in the WP All Import Pro Function Editor: https://www.wpallimport.com/documentation/inline-php/
// Uses the Dom\HTMLElement class for PHP 8.4.0+. https://www.php.net/manual/en/class.dom-htmlelement.php#class.dom-htmlelement
// Code provided by Trey Mills, [email protected]. Updated to use the Dom\HTMLElement class and support UTF-8 characters.
function my_update_images_in_content( $import_id ) {
global $wpdb;
$imported_posts = $wpdb->get_results( "SELECT `post_id` FROM `" . $wpdb->prefix . "pmxi_posts` WHERE `import_id` = '" . $import_id . "'" );
foreach ( $imported_posts as $x_post ) {
$i_post = get_post( $x_post->post_id );
$doc = new \DomDocument('1.0', 'UTF-8');
// Convert encoding to UTF8. Otherwise special characters get mangled on output. For example, a curly apostrophe ’ is output as ’ without mb_convert_encoding.
$doc->loadHTML( mb_convert_encoding( $i_post->post_content, 'HTML-ENTITIES', 'UTF-8' ) );
$imageTags = $doc->getElementsByTagName( 'img' );
if ( $imageTags->length > 0 ) {
foreach( $imageTags as $tag ) {
$img_guid = $tag->getAttribute( 'src' );
$query = "SELECT `ID` FROM `" . $wpdb->prefix . "posts` WHERE `guid` LIKE '%" . $img_guid . "%'";
if ( $result = $wpdb->get_row( $query ) ) {
$tag->setAttribute( 'class', 'wp-image-' . $result->ID );
}
}
$i_post->post_content = $doc->saveHTML();
wp_update_post( $i_post );
}
}
}
add_action( 'pmxi_after_xml_import', 'my_update_images_in_content', 10, 1 );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment