Advertisement
Guest User

WordPress Automatically Generate Alt Text

a guest
Dec 9th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.69 KB | None | 0 0
  1. /**
  2.  * Generate the image alt text on upload
  3.  * Sets image alt text
  4.  * - https://codex.wordpress.org/Plugin_API/Action_Reference/add_attachment
  5.  * - https://developer.wordpress.org/reference/hooks/add_attachment/
  6.  *
  7.  * @param Integer $post_id The Attachment ID
  8.  *
  9.  * @return void
  10.  */
  11. function wp_set_image_alt( $post_id ) {
  12.  
  13.     // If we're not dealing with an image
  14.     if( ! wp_attachment_is_image( $post_id ) ) {
  15.         return;
  16.     }
  17.        
  18.     $title = get_post_field( 'post_title', $post_id );
  19.    
  20.     if( ! empty( $title ) && ! is_wp_error( $title ) ) {
  21.         update_post_meta( $post_id, '_wp_attachment_image_alt', sanitize_text_field( $title ) );
  22.     }
  23. }
  24. add_action( 'add_attachment', 'wp_set_image_alt' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement