下面是代码的更新版本,通过添加将返回的简单检查来避免警告$content
如果是空字符串,则未修改。
原始代码添加<html>
修改后的标记(检查页面源代码),这是我们不想要的。下面的代码也解决了这个问题。
add_filter( \'the_content\', \'wpse_add_img_post_class\' );
function wpse_add_img_post_class( $content ) {
// Bail if there is no content to work with.
if ( ! $content ) {
return $content;
}
// Create an instance of DOMDocument.
$dom = new \\DOMDocument();
// Supress errors due to malformed HTML.
// See http://stackoverflow.com/a/17559716/3059883
$libxml_previous_state = libxml_use_internal_errors( true );
// Populate $dom with $content, making sure to handle UTF-8.
// Also, make sure that the doctype and HTML tags are not added to our
// HTML fragment. http://stackoverflow.com/a/22490902/3059883
$dom->loadHTML( mb_convert_encoding( $content, \'HTML-ENTITIES\', \'UTF-8\' ),
LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
// Restore previous state of libxml_use_internal_errors() now that we\'re done.
libxml_use_internal_errors( $libxml_previous_state );
// Create an instance of DOMXpath.
$xpath = new \\DOMXpath( $dom );
// Get images then loop through and add additional classes.
$imgs = $xpath->query( "//img" );
foreach ( $imgs as $img ) {
$existing_class = $img->getAttribute( \'class\' );
$img->setAttribute( \'class\', "{$existing_class} post-image lazy-load o-image" );
}
// Save and return updated HTML.
$new_content = $dom->saveHTML();
return $new_content;
}