Skip to content

Instantly share code, notes, and snippets.

@moxdev
Created December 16, 2019 18:09
Show Gist options
  • Save moxdev/0771e87a9befcb14a150199b3499f01a to your computer and use it in GitHub Desktop.
Save moxdev/0771e87a9befcb14a150199b3499f01a to your computer and use it in GitHub Desktop.
Add titles to uploaded images in WordPress
/**
* Sets img title of uploaded attachment.
* If no title, will use the alt as a defualt title.
*
* @param array $attr Image tag attributes.
* @param WP_Post $attachment The WP_Post object for the attachment.
* @link https://developer.wordpress.org/reference/hooks/wp_get_attachment_image_attributes/
*
* @return array (maybe) filtered image tag attributes.
*/
function wp_add_img_title( $attr, $attachment = null ) {
$img_title = trim( wp_strip_all_tags( $attachment->post_title ) );
$attr['title'] = $img_title ? $img_title : $attr['alt'];
return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'wp_add_img_title', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment