Last active
December 25, 2019 19:54
-
-
Save RiodeJaneiroo/c1ecb200b5eb9e073b48ed29237f387c to your computer and use it in GitHub Desktop.
[Add title attribute to image – Wordpress] #seo #wordpress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_filter( 'wp_get_attachment_image_attributes', 'add_title_attachment_image', 10, 3 ); | |
function add_title_attachment_image( $attr, $attachment, $size ){ | |
if(empty($attr['title'])) $attr['title'] = $attr['alt']; | |
return $attr; | |
} | |
function add_alt_tags($content) | |
{ | |
global $post; | |
preg_match_all('/<img (.*?)\/>/', $content, $images); | |
if(!is_null($images)) | |
{ | |
foreach($images[1] as $index => $value) | |
{ | |
if(!preg_match('/alt=/', $value) || preg_match('/alt=""/', $value)) | |
{ | |
$new_img = str_replace('<img', '<img title="'.$post->post_title.'" alt="'.$post->post_title.'"', $images[0][$index]); | |
$content = str_replace($images[0][$index], $new_img, $content); | |
} | |
} | |
} | |
return $content; | |
} | |
add_filter('the_content', 'add_alt_tags', 99999); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment