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

https://snxa.com/wp-content/uploads/2020/07/1595512737-e7707646f79ff0a.jpg

将下面的代码添加到当前主题函数模板functions.php中:

  1. add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
  2. function my_set_image_meta_upon_image_upload( $post_ID ) {
  3.  
  4. // Check if uploaded file is an image, else do nothing
  5.  
  6. if ( wp_attachment_is_image( $post_ID ) ) {
  7.  
  8. $my_image_title = get_post( $post_ID )->post_title;
  9.  
  10. // Sanitize the title: remove hyphens, underscores & extra spaces:
  11. $my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $my_image_title );
  12.  
  13. // Sanitize the title: capitalize first letter of every word (other letters lower case):
  14. $my_image_title = ucwords( strtolower( $my_image_title ) );
  15.  
  16. // Create an array with the image meta (Title, Caption, Description) to be updated
  17. // Note: comment out the Excerpt/Caption or Content/Description lines if not needed
  18. $my_image_meta = array(
  19. 'ID' => $post_ID, // Specify the image (ID) to be updated
  20. 'post_title' => $my_image_title, // Set image Title to sanitized title
  21. 'post_excerpt' => $my_image_title, // Set image Caption (Excerpt) to sanitized title
  22. 'post_content' => $my_image_title, // Set image Description (Content) to sanitized title
  23. );
  24.  
  25. // Set the image Alt-Text
  26. update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
  27.  
  28. // Set the image meta (e.g. Title, Excerpt, Content)
  29. wp_update_post( $my_image_meta );
  30.  
  31. }
  32. 代码可以过滤掉图片名称中的空格等多余元素,对之前上传的图片无效。

    代码源自:https://brutalbusiness.com/automatically-set-the-wordpress-image-title-alt-text-other-meta

  33. }


微信扫描下方的二维码阅读更多精彩内容

https://snxa.com/wp-content/plugins/rest-api-to-wechat/images/qrcode/qrcode-98.png