I wrote this function but it doesn't seem to be saving the $dom
. If I check the attribute after I set it, it is correct, but it just doesn't make it to the final save.
function tj_add_alts( $content ) {
$dom = new DOMDocument();
$dom->loadHTML($content);
foreach ($dom->getElementsByTagName( 'img' ) as $node) {
if ( trim( $node->getAttribute( 'alt' ) ) == "" ) {
$img = $node->getAttribute( 'src' );
$file_name = pathinfo($img, PATHINFO_FILENAME);
$name = preg_replace( '/[^A-Za-z0-9 ]/', ' ', $file_name);
$name = preg_replace( '/\s{2,}/', ' ', $name);
$node->setAttribute( 'alt', $name );
}
}
$content = $dom->saveHTML();
return $content;
}
UPDATE: It looks like the problem is that DomDocument automatically adds the doctype
declaration and <body>
and <head>
tags, which I don't want. Is there a way to get ride of those?