您可以尝试以下测试插件,该插件使用domDocument
类,以查看它如何在HTML上工作。
它假设PHP 5.4+和LibXML 2.7.8+。
<?php
/**
* Plugin Name: Add Missing Image Title Attributes
* Description: For posts in the main loop (Assumes PHP 5.4+ with LibXML 2.7.8+)
* Plugin URI: http://wordpress.stackexchange.com/a/188560/26350
* Author: Birgir Erlendsson (birgire)
* Version: 0.0.1
*/
namespace wpse\\birgire;
add_action( \'init\', function()
{
$o = new AddMissingImgTitle;
$o->activate( new \\domDocument );
} );
class AddMissingImgTitle
{
private $dom;
public function activate( \\domDocument $dom )
{
$this->dom = $dom;
add_filter( \'the_content\', [ $this, \'the_content\' ] );
}
public function the_content( $html )
{
if( ! in_the_loop() )
return $html;
if( false === strpos( $html, \'<img\' ) )
return $html;
return $this->process( $html );
}
private function process( $html )
{
// Handle utf8 strings
// See http://php.net/manual/en/domdocument.loadhtml.php#95251
$html = \'<?xml encoding="UTF-8">\' . $html;
// Load without HTML wrapper
// See https://stackoverflow.com/a/22490902/2078474
$this->dom->loadHTML( $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
// Fetch all image tags:
$images = $this->dom->getElementsByTagName( \'img\' );
foreach ( $images as $image )
{
// Add the title attribute if it\'s missing (using the post title):
if( \'\' === $image->getAttribute( \'title\' ) )
$image->setAttribute( \'title\', esc_attr( get_the_title() ) );
}
return str_replace( \'<?xml encoding="UTF-8">\', \'\', $this->dom->saveHTML() );
}
} // end class
对于旧版本的LibXML,您可以查看
this question 无需
LIBXML_HTML_NOIMPLIED
和
LIBXML_HTML_NODEFDTD
选项。