Advertisement
Alfonso_Ojeda

Poner automático el alt y el title al subir una imagen

Jul 9th, 2020
1,051
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. /* --------------------------------------------------------------------------------------
  2.  
  3. Hola amiguetes. Con este código en vuestro functions.php se colocará el nombre del archivo en los campos "alt" y "title" al subir una imagen a vuestro Wordpress. Es configurable, os comparto el código completo en el que también se rellena el Excerpt y la Description de la imagen, si no lo queréis, borrad esa línea.
  4.  
  5. Cualquier cosilla por aquí estoy: Twitter @aro_mdz
  6.  
  7. /// Nota: os dejo también un programilla muy chulo para renombrar imágenes en bulk => https://filebin.net/34ncm77nd6qp4ett
  8. //// Nota 2: no sé el autor del código, ni siquiera sé si un código tiene derechos de autor. Si alguien reconoce su estilo de tecleo y quiere reclamar autoría, que hable con Julio Rodríguez: @thisjrodriguez
  9.  
  10. --------------------------------------------------------------------------------------*/
  11. add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
  12. function my_set_image_meta_upon_image_upload( $post_ID ) {
  13.  
  14. // Check if uploaded file is an image, else do nothing
  15.  
  16. if ( wp_attachment_is_image( $post_ID ) ) {
  17.  
  18. $my_image_title = get_post( $post_ID )->post_title;
  19.  
  20. // Sanitize the title: remove hyphens, underscores & extra spaces:
  21. $my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $my_image_title );
  22.  
  23. // Sanitize the title: capitalize first letter of every word (other letters lower case):
  24. $my_image_title = ucwords( strtolower( $my_image_title ) );
  25.  
  26. // Create an array with the image meta (Title, Caption, Description) to be updated
  27. // Note: comment out the Excerpt/Caption or Content/Description lines if not needed
  28. $my_image_meta = array(
  29. 'ID' => $post_ID, // Specify the image (ID) to be updated
  30. 'post_title' => $my_image_title, // Set image Title to sanitized title
  31. 'post_excerpt' => $my_image_title, // Set image Caption (Excerpt) to sanitized title
  32. 'post_content' => $my_image_title, // Set image Description (Content) to sanitized title
  33. );
  34.  
  35. // Set the image Alt-Text
  36. update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
  37.  
  38. // Set the image meta (e.g. Title, Excerpt, Content)
  39. wp_update_post( $my_image_meta );
  40.  
  41. }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement