获得搜索引擎的流量,是我们创建 WordPress 网站的重要目的之一。而要获得搜索引擎流量,我们需要做好网站的 SEO 工作,提升网站的收录量,提升网站关键词的排名。
ALT 是替代文本的缩写,用于在图像无法正确显示时,提供的对图像的文字描述。为图片增加 ALT 属性,就是对网站所做 SEO 优化的重要手段。
如何在 WordPress 中自动为图像添加替代文本?
通过 Bulk Auto Image Alt Text 插件实现
可以通过一款名为 Bulk Auto Image Alt Text (BIALTY) 的插件,来实现自动添加 WordPress 图像替代文本。该插件也适用于“Woocommerce 商店”。因此,如果您有一个使用 woocommerce 构建的在线商店,那么此插件也可以自动为 woocommerce 产品图像添加替代文本。
通过自定义代码实现
要通过添加自定义代码,来实现自动为图片添加 ALT 替代文本,需要在当前使用主题的 Functions.php 文件中,添加本文提供的自定义代码。在 Functions.php 中添加代码之前,记得对文件做好备份。我们建议先创建当前主题的子主题,然后在子主题的 Functions.php 文件中添加自定义代码。
扩展阅读:
具体操作步骤如下:
第一步:登录到 wordpress 管理仪表盘,然后转到“外观”-“主题文件编辑器”。
第二步:进入主题文件编辑页面后,选择当前主题的子主题,然后从右侧列表中选择 functions.php 文件。
第三步:将以下代码添加到 functions.php 文件中。
add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
function my_set_image_meta_upon_image_upload( $post_ID ) {
// Check if uploaded file is an image, else do nothing
if ( wp_attachment_is_image( $post_ID ) ) {
$my_image_title = get_post( $post_ID )->post_title;
// Sanitize the title: remove underscores & extra spaces:
$my_image_title = preg_replace( '%\s*[_\s]+\s*%', ' ', $my_image_title );
// Sanitize the title: capitalize first letter of every word (other letters lower case):
$my_image_title = ucwords( strtolower( $my_image_title ) );
// Create an array with the image meta (Title, Caption, Description) to be updated
// Note: comment out or delete the Excerpt/Caption or Content/Description lines below if not needed
$my_image_meta = array(
'ID' => $post_ID, // Specify the image (ID) to be updated
'post_title' => $my_image_title, // Set image Title to sanitized title
'post_excerpt' => $my_image_title, // Set image Caption (Excerpt) to sanitized title
'post_content' => $my_image_title, // Set image Description (Content) to sanitized title
);
// Set the image Alt-Text
update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
// Set the image meta (e.g. Title, Excerpt, Content)
wp_update_post( $my_image_meta );
}
}
作者:牛奇网,本站文章均为辛苦原创,在此严正声明,本站内容严禁采集转载,面斥不雅请好自为之,本文网址:https://www.niuqi360.com/wordpress/how-to-add-media-title-and-alt-tags-automatically-in-wordpress/