Forked from jeremytarpley/wp-update-image-asset-id-php-5-to-8.php
Created
December 31, 2024 19:12
-
-
Save trey8611/3255b60b65cc46650212d2abe1326937 to your computer and use it in GitHub Desktop.
WP All Import Pro, update image asset IDs after migrating - using DOMDocument::loadHTML
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 DOMDocument::loadHTML for PHP 5-8. | |
// Code provided by Trey Mills, [email protected]. Updated to 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 ); | |
// Note from https://www.php.net/manual/en/domdocument.loadhtml.php | |
// Warning Use Dom\HTMLDocument to parse and process modern HTML instead of DOMDocument. | |
$doc = new DOMDocument(); | |
$doc->encoding = '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' ), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD ); | |
$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