How to truncate alt text for featured images on content archives in Genesis

Posted on
5/5 - (408 votes)

In Genesis Facebook group a user asked:

I have very long post titles and when I did an accessibility test, there were warnings that the alt tags were too long. So I used the genesis_get_image filter and re-created the image. Is there a better way? I tried the standard WP ‘post_thumbnail_html’ but that only worked for non-Genesis loops, like in Bill Erickson’s display_posts_shortcode (love that!).

In this article I show how we can

  1. add a function to truncate post titles
  2. remove the standard featured image output by Genesis per theme settings on content archives
  3. add custom featured image output in which alt text of featured image is set to truncated post title text

Sample screenshots for a post titled “Sample Post With Threaded Comments”:

Add the following in child theme’s functions.php:

// Function to truncate post titles
function customTitle( $limit ) {

    $title = get_the_title( $post->ID );

	if ( strlen( $title ) > $limit ) {
      $title = substr( $title, 0, $limit ) . '...';
    }

    return $title;
}

// genesis_entry_header action hook is used here because it is the one immediately above genesis_entry_content. Remember: Hook as late as possible.
add_action( 'genesis_entry_header', 'sk_custom_post_image' );
function sk_custom_post_image() {

	// if we are on a content archive page and featured images are set to be shown on content archives in Genesis theme settings
	if ( ! is_singular() && genesis_get_option( 'content_archive_thumbnail' ) ) {

		// remove the standard featured image output by Genesis per theme settings
		remove_action( 'genesis_entry_content', 'genesis_do_post_image', 8 );

		// add custom featured image output
		add_action( 'genesis_entry_content', 'sk_do_post_image', 8 );

	}

}

// Function to set the alt text of featured image to truncated post title text
function sk_do_post_image() {

	$img = genesis_get_image( array(
		'format'  => 'html',
		'size'    => genesis_get_option( 'image_size' ),
		'context' => 'archive',
		'attr'    => genesis_parse_attr( 'entry-image', array ( 'alt' => customTitle( 20 ) ) ),
	) );

	if ( ! empty( $img ) ) {
		printf( '<a href="%s" aria-hidden="true">%s</a>', get_permalink(), $img );
	}

}

Change 20 in the above the number of characters you wish to be shown.