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

知更鸟 WordPress21.1K阅读模式

WordPress上传图片时手动给图片添加替代文本(Alt)和图像描述有些麻烦,可以通过本文的方法自动将图片名称设置为WordPress图像标题、说明和图像描述,如图:文章源自知更鸟-https://zmingcx.com/wordpress-pictures-automatically-add-alt.html

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

 文章源自知更鸟-https://zmingcx.com/wordpress-pictures-automatically-add-alt.html

WordPress上传图片自动添加Alt和图像描述文章源自知更鸟-https://zmingcx.com/wordpress-pictures-automatically-add-alt.html

将下面的代码添加到当前主题函数模板functions.php中:文章源自知更鸟-https://zmingcx.com/wordpress-pictures-automatically-add-alt.html

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 );

	} 
}

代码可以过滤掉图片名称中的空格等多余元素,对之前上传的图片无效。文章源自知更鸟-https://zmingcx.com/wordpress-pictures-automatically-add-alt.html

代码源自:https://brutalbusiness.com/automatically-set-the-wordpress-image-title-alt-text-other-meta文章源自知更鸟-https://zmingcx.com/wordpress-pictures-automatically-add-alt.html

weinxin
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
评论  2  访客  2
    • 免费收录网站
      免费收录网站 4

      有省不少事,越来越智能了。

      • 佛系软件
        佛系软件 4

        我图片是外链引用的。网站不是所有的图片都会有啊,比如相册就没有

      匿名

      发表评论

      匿名网友 填写信息

      :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

      确定