WordPress上传图片自动添加Alt和图像描述
首页>>技术教程>>正文
本篇文章更新于 2021-11-14 21:02:16
本篇文章更新于 2021-11-14
WordPress上传图片自动添加Alt和图像描述

WordPress上传图片时手动给图片添加替代文本(Alt)和图像描述有些麻烦,可以通过本文的方法自动将图片名称设置为WordPress图像标题、说明和图像描述,如图:

WordPress上传图片自动添加Alt和图像描述

将下面的代码添加到当前主题函数模板

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 hyphens, 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 the Excerpt/Caption or Content/Description lines 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 );
 
	} 
}

代码可以过滤掉图片名称中的空格等多余元素,对之前上传的图片无效。

历史上的今天
11月
14
技术教程

解决升级WordPress时提示:另一更新正在进行

2021-11-14 19:55:49

技术教程

WordPress自动给图片添加alt和title标签

2021-11-14 21:13:36

重要说明

本站资源大多来自网络,如有侵犯你的权益请联系管理员或给邮箱发送邮件zhouqiuqiu123@foxmail.com 我们会第一时间进行审核删除。站内资源为网友个人学习或测试研究使用,未经原版权作者许可,禁止用于任何商业途径!请在下载24小时内删除!


如果遇到评论下载的文章,评论后刷新页面点击对应的蓝字按钮即可跳转到下载页面本站资源少部分采用7z压缩,为防止有人压缩软件不支持7z格式,7z解压,建议下载7-zip(点击下载),zip、rar解压,建议下载WinRAR(点击下载)

敏而好学,不耻下问。——孔子