Use Rank Math Focus Keyword As Alt Text / Title For Images

In a previous doc we looked at how to use Yoast Focus Keyword as attributes for Images. A new and upcoming player in the SEO space, Rank Math SEO plugin, also uses focus keywords.

This doc will explain how to use Rank Math focus keyword in the image attributes generated by Image Attributes Pro.

Similar to Yoast, Rank Math also stores the focus keyword as post meta and can be accessed using the get_post_meta WordPress function.

We will retrieve this data and use the iaffpro_image_attributes filter to modify the generated image attributes.

Example Snippet

Here is how to extract the Rank Math 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 Rank Math 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_rank_math_focus_kw_image_attributes( $attributes, $image_id, $parent_post_id ) {
	 
	// Get Rank Math focus keyword
	$rank_math_focus_keyword = '';
	
	if ( $parent_post_id !==0 ) {
		$rank_math_focus_keyword = get_post_meta( $parent_post_id, 'rank_math_focus_keyword', true );
	}
	
	// Do nothing if the focus keyword is empty
	if ( $rank_math_focus_keyword === '' ) {
		return $attributes;
	}
	
	$attributes['title'] = $attributes['title'] . ' - ' . $rank_math_focus_keyword;
	$attributes['caption'] = $rank_math_focus_keyword . ' - ' . $attributes['caption'];
	$attributes['description'] = $rank_math_focus_keyword;
	$attributes['alt_text'] = $attributes['alt_text'] . ' - ' . $rank_math_focus_keyword;
	
	return $attributes;
}
add_filter( 'iaffpro_image_attributes', 'prefix_iap_rank_math_focus_kw_image_attributes', 10, 3 );
  • If you look closely, for the image title ($attributes['title']) and image alt text ($attributes['alt_text']), Rank Math focus keyword is used as a post-fix.
  • For the image caption ($attributes['caption']), Rank Math focus keyword is used as a pre-fix.
  • The image description ($attributes['description']) is replaced by the Rank Math 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.