Advertisement
aouwalcmc

Image Name, File Uploader

Jun 25th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. /* Automatically set the image Title, Alt-Text, Caption & Description upon upload
  2. --------------------------------------------------------------------------------------*/
  3. add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
  4. function my_set_image_meta_upon_image_upload( $post_ID ) {
  5.  
  6. // Check if uploaded file is an image, else do nothing
  7.  
  8. if ( wp_attachment_is_image( $post_ID ) ) {
  9.  
  10. $my_image_title = get_post( $post_ID )->post_title;
  11.  
  12. // Sanitize the title: remove hyphens, underscores & extra spaces:
  13. $my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $my_image_title );
  14.  
  15. // Sanitize the title: capitalize first letter of every word (other letters lower case):
  16. $my_image_title = ucwords( strtolower( $my_image_title ) );
  17.  
  18. // Create an array with the image meta (Title, Caption, Description) to be updated
  19. // Note: comment out the Excerpt/Caption or Content/Description lines if not needed
  20. $my_image_meta = array(
  21. 'ID' => $post_ID, // Specify the image (ID) to be updated
  22. 'post_title' => $my_image_title, // Set image Title to sanitized title
  23. 'post_excerpt' => $my_image_title, // Set image Caption (Excerpt) to sanitized title
  24. 'post_content' => $my_image_title, // Set image Description (Content) to sanitized title
  25. );
  26.  
  27. // Set the image Alt-Text
  28. update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
  29.  
  30. // Set the image meta (e.g. Title, Excerpt, Content)
  31. wp_update_post( $my_image_meta );
  32.  
  33. }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement