Use Yoast Focus Keyword As Alt Text / Title For Images

The popular SEO plugin, Yoast, allows you to select a keyword for each page. You can enter a keyword or keyphrase that you like the page to rank for on Google.

With Image Attributes Pro, you can use Yoast focus keyword in any of the image attributes (alt text, image title, image description or image caption). Here is how.

To do so, we need to take advantage of the iaffpro_image_attributes filter. If code isn’t your thing, don’t worry, there is a ready to use snippet later in this page.

Yoast stores the focus keyword as a post meta and can be easily retrieved using the WordPress function get_post_meta.

Example Snippet

Here is how to extract the Yoast focus keyword and add it as image attribute with Image Attributes Pro.

Copy paste the following code into the functions.php of your active theme.

/**
 * Add Yoast Focus Keyword as Image Alt Text, Title, Caption and Description
 *
 * @param $attributes 		(array) Associative array of image attributes.
 * @param $image_id 		(int) ID of the current image.
 * @param $parent_post_id	(int) ID of the post the image is inserted into. 0 for images not attached to a post.
 * 
 * @author Arun Basil Lal
 * @link https://imageattributespro.com/codex/iaffpro_image_attributes/‎
 */
 function prefix_iap_yoast_focus_kw_image_attributes( $attributes, $image_id, $parent_post_id ) {
	 
	// Get Yoast focus keyword
	$yoast_focus_keyword = '';
	
	if ( $parent_post_id !==0 ) {
		$yoast_focus_keyword = get_post_meta( $parent_post_id, '_yoast_wpseo_focuskw', true );
	}
	
	// Do nothing if the focus keyword is empty
	if ( $yoast_focus_keyword === '' ) {
		return $attributes;
	}
	
	$attributes['title'] = $attributes['title'] . ' - ' . $yoast_focus_keyword;
	$attributes['caption'] = $yoast_focus_keyword . ' - ' . $attributes['caption'];
	$attributes['description'] = $yoast_focus_keyword;
	$attributes['alt_text'] = $attributes['alt_text'] . ' - ' . $yoast_focus_keyword;
	
	return $attributes;
}
add_filter( 'iaffpro_image_attributes', 'prefix_iap_yoast_focus_kw_image_attributes', 10, 3 );
  • If you look closely, for the image title ($attributes['title']) and image alt text ($attributes['alt_text']), Yoast focus keyword is used as a post-fix.
  • For the image caption ($attributes['caption']), Yoast focus keyword is used as a pre-fix.
  • The image description ($attributes['description']) is replaced by the Yoast focus keyword in itself.

Hope these examples help you customize the snippet to meet your needs. If you need help customizing the snippet above, please feel free to write to support.