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

发布时间:5个月前 来源:互联网

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

将下面的代码添加到当前主题函数模板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 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 );  }  }

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

特别声明:以上文章来源互联网,由环络收集整理,如内容、图片有任何版权问题,请联系我们进行处理。

很高兴能够帮助您

欢迎联系我们,希望能为您有所帮助!

很高兴能够帮助您

搜索犹豫不如咨询1次

主营项目:网站建设,手机网站,响应式网站,SEO优化,小程序开发,版权登记,商标注册等

立即咨询 13513822110
在线客服
Hi,我来帮您!