255 0

要在WordPress中自动为文章内容的图片添加文章标题作为alt属性,可以通过以下方法实现:

可以将以下PHP代码添加到你的主题的functions.php文件中,这段代码会检查文章内容中的<img>标签,如果这些标签没有alt属性或者alt属性为空,它会为这些标签添加alttitle属性,属性的值是文章的标题加上图片的序号。

//添加文章标题作为alt属性
function add_image_alt_title_tags($content) {
global $post;
$post_title = $post->post_title;
$pattern = '/<img(.*?)\/>/i';
preg_match_all($pattern, $content, $matches);
$image_count = count($matches[0]);
foreach ($matches[0] as $index => $img_tag) {
if (strpos($img_tag, ' alt=') === false || preg_match('/ alt=["\']\s*["\']/', $img_tag)) {
if ($image_count === 1) {
// 如果只有一张图片,不添加序号
$replacement = preg_replace('/<img/', '<img alt="' . $post_title . '" title="' . $post_title . '"', $img_tag);
} else {
// 如果有多张图片,添加序号
$replacement = preg_replace('/<img/', '<img alt="' . $post_title . '-' . ($index + 1) . '" title="' . $post_title . '-' . ($index + 1) . '"', $img_tag);
}
$content = str_replace($img_tag, $replacement, $content);
}
}
return $content;
}
add_filter('the_content', 'add_image_alt_title_tags');

 

自动为WordPress文章中的图片添加alt属性,提高网站的SEO友好性和无障碍访问性。

相关文章

通往AGI之路 - 全面系统、易于理解的 AI 学习路径,优质中文 AI 知识库
2025年4月最新中国税收居民身份证明申请教程,适用于Google AdSense及其他跨国收入场景
如何禁止 Windows 11 23H2 版本自动更新 24H2版本???
如何恢复 Windows 11 系统登录用户半透明头像???
Windows 11 安装时如何跳过“系统联网登录微软账号/设置密保安全问题” 快速安装系统
虚拟机安装 Windows 11 出现 “Press any key to boot from CD or DvD……” 要如何正确安装???

发布评论