WordPress文章中的图片添加alt属性,很多时候都是因为SEO,但很多人包括小编在内,很多时候也是不会去添加的。
相关阅读:
1、为WordPress文章图片自动添加alt与title属性
2、WordPress图片怎么自动添加alt和title属性
今天追格小编教你如何将title标签作为文章图片的alt属性。
function callback($buffer) {
/* modify buffer here, and then return the updated code*/
$title='';
$res = preg_match('/<title>(.*?)</title>/', $buffer, $title_matches);
if ($res) {
/*Clean up title: remove EOL's and excessive whitespace.*/
$title = preg_replace('/s+/', ' ', $title_matches[1]);
$title = trim($title);
}
preg_match_all('/<img (.*?)/>/', $buffer, $images);
if(!is_null($images)) {
foreach($images[1] as $index => $value) {
preg_match('/alt="(.*?)"/', $value, $img);
preg_match('/alt='(.*?)'/', $value, $img2);
if(!is_null($images)) {
if((!isset($img[1]) || $img[1] == '') || (!isset($img2[1]) || $img2[1] == '')) {
$new_img = str_replace('<img', '<img alt="'.$title.'"', $images[0][$index]);
$buffer = str_replace($images[0][$index], $new_img, $buffer);
}
}
}
}
return $buffer;
}
function buffer_start() {
ob_start();
}
function buffer_end() {
echo callback(ob_get_clean());
}
add_action('wp', 'buffer_start', 0); add_action('wp_footer', 'buffer_end');
上面代码添加到当前WordPress模板的functions.php文件中即可。
需要注意的是,上面代码中虽有缓冲区代码,可能还会降低效率,建议安装静态缓存插件。
-
WordPress 6.5 新功能 - 字体库字体库是 WordPress 6.5 的亮点之一
-
WordPress6.5新功能-声明式插件依赖在 WordPress 6.5 中,插件依赖变简单了
-
WordPress 6.5 新功能 - 支持 AVIFWordPress 6.5 新功能 - 支持 AVIF
-
WordPress 6.5移除区块样板菜单项的方法WordPress 6.5新增的区块样板菜单项,可将不同区块组合成一个新的区块模板,方便重复使用。
-
WordPress做多语言企业网站近期常用小伙伴问追格小编,有没有计划做双语WordPress企业官网主题。
-
WordPress插件:LiteSpeed Cache 缓存插件LiteSpeed Cache是一款实用的WordPress缓存插件,专为使用LiteSpeed服务器的用户设计。它能显著提高网站加载速度,改善用户体验。
暂无评论,抢个沙发...