我需要为数百张图片添加图片 alt 标签。问题是这需要很长时间,而且似乎有更简单的解决方案。
我已经能够使用 javascript 在某种程度上实现这一点,如下所示:
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
$('img').each(function(){
var $img = $(this);
var filename = $img.attr('src')
if (typeof attr == typeof undefined || attr == false) {
$img.attr('alt', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));
}
});
});
//]]>
</script>
这正是我想要的,例如,如果我有这张图片:
<img src="http://mywebsite.com/images/the-image1.jpg" />
然后 javascript 会像这样自动添加 alt:
<img src="http://mywebsite.com/images/the-image1.jpg" alt="the-image1" />
好吧,这一切都很好,但现在我想用 PHP 来代替,因为问题是这只是将标签添加到前端,这意味着它从页面源代码中不可见(仅inspect 元素),这意味着搜索引擎不会看到 alt 标记,这意味着唯一的方法是使用 php 将其直接放入页面中。
那么我如何使用 php 来完成上述 javascript 解决方案呢?
最佳答案
文件名是否始终提供有意义的 slug?如果没有,您最好只使用空的 alt 标签。网络爬虫已经获取了图像文件名,因此添加最后一位只有在它实际上是对图像的描述时才会有所帮助。 (也不是 100% 正确,它不会通过 JS 编入索引,一些机器人,尤其是 Google,会在某种程度上解析 JavaScript。)
如果文件名没有描述性,它可能弊大于利(对于 SEO 和屏幕阅读器)。如果您打算继续使用此方案,我假设您正在或将会提供描述性文件名。
我假设图像不是以某种方式进行内容管理的,您可以从 alt(和/或 longdesc)属性的标题或描述中提取?
如果它是一次性修复,同样取决于命名的质量,它可能没问题。几百张图片可能不会花那么长时间,而且总有 [广告已删除] :)
Alternative text serves several functions:
- It is read by screen readers in place of images allowing the content and function of the image to be accessible to those with visual or certain cognitive disabilities.
- It is displayed in place of the image in browsers if the image file is not loaded or when the user has chosen not to view images.
- It provides a semantic meaning and description to images which can be read by search engines or be used to later determine the content of the image from page context alone.
关于php - 如果缺少图像文件名,如何使用 php 自动添加图像 "alt"属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38537609/