我有一个客户的网站,他们想在那里动态添加图像标题属性到没有标题属性的图像。因此,如果title属性为空,则添加一个帖子标题。我将如何实现这一点?
有效地:<img src=img.jpg title=[wp-post-title-here] />
我有一个客户的网站,他们想在那里动态添加图像标题属性到没有标题属性的图像。因此,如果title属性为空,则添加一个帖子标题。我将如何实现这一点?
有效地:<img src=img.jpg title=[wp-post-title-here] />
您可以尝试以下测试插件,该插件使用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
选项。如果我们可以假设这对于模板中的图像是正确的,并且您只关心页面/帖子正文内容,那么您可以在保存任何帖子或页面时使用过滤器(https://codex.wordpress.org/Plugin_API/Action_Reference/save_post ) 要扫描内容
由于此操作在帖子保存后立即触发,因此您可以使用get\\u post($post\\u id)轻松访问此帖子对象
然后,您应该能够搜索所有图像标记<img
, 如果他们没有这个短语title="
在下一个之前>
, 在后面插入<img
你的title="post title here"
- 不要忘记在整个功能运行后重新“保存”帖子。
为了做到这一点,我会将post字符串拆分为子字符串,然后重新组装它们,但这里不适合为您编写所有代码。
或者,当代码显示到页面时,可以通过过滤get\\u内容或类似内容对图像标记进行类似的扫描,但在查看者的页面加载方面,正确保存到数据库更有意义。
图像标题属性实际上必须在数据库中吗?如果仅仅是显示文本的问题,例如在照片库中,那么使用jQuery函数不符合您的目的吗?类似于:
$(document).ready(function() {
$(\'img\').each(function() {
if ($(this).attr(\'title\') === undefined) {
var title = $(\'h1\').text();
$(this).attr(\'title\', title);
}
});
});
这意味着你想在右上角加载该图像。。。将下面的代码放置在需要图像的位置
<?php
$post_id = 75;
$thumbnail_id = 112;
if(!empty(get_the_title($thumbnail_id))){
echo \'<img src="img.jpg" title="\'.get_the_title($thumbnail_id).\'" />\';
}
else{
echo \'<img src="img.jpg" title="\'.get_the_title($post_id).\'" />\';
}
?>
我希望它对你有用。。。我的主题存档中有以下代码。php:<?php the_archive_title( \'<h1 class=\"page-title\">\', \'</h1>\' ); ?> 这给了我诸如“类别:俄罗斯”、“标签:美国”、“作者:约翰”之类的标题。我想删除“Category:”、“Tag:”和“Author:”部分,只显示类别、标记和作者名称。有人知道如何做到这一点吗?非常感谢。