Quantcast
Channel: Michael (aka alchymyth) – TransformationPowerTools
Viewing all articles
Browse latest Browse all 12

Title Attribute for Post Thumbnail

$
0
0

two men shake hands - bronze statues in Calagary/BCThe ‘featured image’ in WordPress automatically outputs the image alt attribute, but no title attribute.

Those two attributes are used for different reasons:
– the alt attribute is used to output alternative information if the image is inaccessible, for instance if the user has opted not to show images in the site, or for screen readers for accessibility reasons;
– the title attribute would present additional information about the image, and is shown by some browsers when you hover over the image.

For a WordPress ‘featured image’, the code below is taking the image title as you see it in the media library,  to be used as the title attribute.

The influence on search engine optimisation is not clear – it seems that the alt attribute is given more importance than the title attribute.

Back to the coding – To add the image title of the featured image as the title attribute to the img tag, a little filter function is needed, added  to the  ‘post_thumbnail_html’ filter.

Instead of just adding the code to functions.php of your theme, where it would get lost when you switch themes, it is more universal to create a basic plugin:

<?php
/*
Plugin Name: Featured Image Title Attribute Output
Plugin URI: n/a
Description: adds the image title as the title attribute to the 'featured image' output.
Version: 1.0
Author: alchymyth
Author URI: http://www.transformationpowertools.com/wordpress
License: GPL2
*/

add_filter('post_thumbnail_html','add_post_thumbnail_title_attribute',10,3);

function add_post_thumbnail_title_attribute($html, $post_id, $post_thumbnail_id) {

if( $html == '' ) {
return $html;
} else {
$out = $html;
$thumbnail_image = get_posts(array('p' => $post_thumbnail_id, 'post_type' => 'attachment'));

if ($thumbnail_image && isset($thumbnail_image[0])) {

$title = $thumbnail_image[0]->post_title;
if($title) {
$output = ' title="' . esc_attr($title) . '" ';
$out = str_replace( 'class=', $output . 'class=', $html );
}
}
}
return $out;
}
?>

Upload this as a appropriately named file into the plugins folder of your WordPress installation, and activate it like any other plugin from dashboard – plugins.


Viewing all articles
Browse latest Browse all 12

Trending Articles