更新现有对象(或数组)时,如果通过引用工作,foreach循环要注意的事项
默认情况下,foreach循环创建项的副本并在其上运行。要使用实际对象,应在前面添加
我还注意到在实际的dom分配中使用临时变量:
创建临时变量并使用其结果插入对象
但它应该行得通
我还让saveHTML脱离了循环,因为不需要中间保存
希望有帮助
下面是&img
add_filter('the_content', function ($content) {
$dom = new DOMDocument();
$dom->loadHTML($post->post_content);
foreach($dom->getElementsByTagName( 'img' ) as &$img) {
if ( $img->hasAttribute( 'src' )) {
$src_attr = $img->getAttribute( 'src' );
$noscript = $dom->createElement( 'noscript' );
$noscript_node = $img->parentNode->insertBefore( $noscript, $img );
$noscript_img = $dom->createElement( 'IMG' );
$new_img = $noscript_node->appendChild( $noscript_img );
$new_img->setAttribute( 'src', $src_attr );
}
};
$content = $dom->saveHTML();
return $content;
});