Created
December 30, 2024 20:52
-
-
Save jeremytarpley/4070c88d29f44684c0a0ee82af79aa5b to your computer and use it in GitHub Desktop.
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 | |
// 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