Hi everyone,
I also have the same problem: lots of lightbox-like only deal with the anchor title, not with the img title.
By the way, adding a single image in a post already did the same in previous WP releases: no title is set for the link and we have to do it manually. The difference is that we can do it for a single image, it is impossible for a native WP Galley!
So, I made a very dirty hook that I use in my theme’s “functions.php”:
function add_img_title_to_anchor($content) {
/* Find internal links */
//Check the page for linked images
$search = '/<a ([^>]*?)><img ([^>]*?)\/><\/a>/i';
preg_match_all( $search, $content, $matches, PREG_SET_ORDER);
//Check which attachment is referenced
foreach ($matches as $val) {
// Only if the Link doesn't already have a Title attribute, we work
if (!preg_match("#title=#", $val[1])) {
// Find all Link attributes and sanitize the Href att
$anchor_temp = preg_match_all("#([a-z-]+?)=(['\"]{1})([^'\"]*)(['\"]{1})#", $val[1], $matches_anchor);
foreach ($matches_anchor[1] as $key => $value) {
$anchor_atts[$value] = $matches_anchor[3][$key];
}
// Find all Image attributes
$img_temp = preg_match_all("#([a-z-]+?)=([\"]{1})([^\"]*)([\"]{1})#", $val[2], $matches_img);
foreach ($matches_img[1] as $key => $value) {
$img_atts[$value] = $matches_img[3][$key];
}
// Get the Image Title attribute and copy it to the Link attributes
// Case 1. If Image Title exists we use it
if (isset($img_atts["title"]) && $img_atts["title"] != "") {
$anchor_atts["title"] = $img_atts["title"];
}
// Case 2. If no we use the Alt attribute
else {
$anchor_atts["title"] = $img_atts["alt"];
}
// Rebuilt the HTML tags
$anchor_attributes = array();
foreach ($anchor_atts as $key => $value) {
$anchor_attributes[] = $key . '="' . $value . '"';
}
$img_attributes = array();
foreach ($img_atts as $key => $value) {
$img_attributes[] = $key . '="' . $value . '"';
}
// Replace the previous tags by the new
$replacement = '<a ' . implode(" ", $anchor_attributes) . '><img ' . implode(" ", $img_attributes) . ' /></a>';
$content = str_replace($val[0], $replacement, $content);
}
}
return $content;
}
/* Apply the Filter */
add_filter('the_content', 'add_img_title_to_anchor', 200);
I’m not a very good dev, so use it, fix it if needed, improve it, modify it or whatever you want.
I’ll keep track of this thread to see if someone has better ideas than me ?? ..
By the way, this lack of the title attribute in the tag associated to images is still a problem and I hope that someone will fix it. A way should be by an option in the admin panel to let us choose if we want automatic titles or not in the links for images…
And WP native gallery shoud also have this kind of option, at least for manual titling… (And I apologize for my bad english)
Regards,
Johan