How to set specific image sizes for Yoast SEO share images

Updated on

I’ve always found the Yoast SEO plugin’s social media options to be a little frustrating. All I wanted was to be able to specify the correct sizes for the image that was shared on Facebook and Twitter. Sometimes due to the image’s size it would display the incorrect card on Twitter.

This became especially frustrating when it came to administrating a site that multiple people were working on and uploading images to. I set out to define specific sizes for both Facebook and Twitter share images and make sure that that was the image that was associated when the post was shared.

This is the snippet I came up with.

/**
 * Adds optimal image sizes for sharing on Facebook and Twitter.
 */
function add_share_image_sizes() {
	add_image_size( 'facebook-share', 1200, 630, true );
	add_image_size( 'twitter-share', 1024, 512, true );
}
add_action( 'after_setup_theme', 'add_share_image_sizes' );

/**
 * Sets image size for Yoast to use for Facebook shares.
 */
function set_yoast_facebook_share_image_size() {
	return 'facebook-share';
}
add_filter( 'wpseo_opengraph_image_size', 'set_yoast_facebook_share_image_size' );

/**
 * Sets image size for Yoast to use for Twitter shares.
 */
function set_yoast_twitter_share_image_size() {
	return 'twitter-share';
}
add_filter( 'wpseo_twitter_image_size', 'set_yoast_twitter_share_image_size' );

First thing was first, I needed to specify the correct sizes and make sure that when a new image was uploaded to the Media Library, WordPress would create the correct size. For Facebook, the correct size for a share image is 1200 pixels by 630 pixels. For Twitter its 1024 pixels by 512 pixels.

Next, since I wanted to specify the exact correct size I wrote two separate functions for each platform. If you don’t mind sharing the same image size on both platforms, you can use a single function and call it on both filters like so.

/**
 * Adds optimal image sizes for sharing on social media.
 */
function add_share_image_sizes() {
	add_image_size( 'social-share', 1200, 630, true );
}
add_action( 'after_setup_theme', 'add_share_image_sizes' );

/**
 * Sets image size for Yoast to use for social shares.
 */
function set_yoast_social_share_image_size() {
	return 'social-share';
}
add_filter( 'wpseo_opengraph_image_size', 'set_yoast_social_share_image_size' );
add_filter( 'wpseo_twitter_image_size', 'set_yoast_social_share_image_size' );

Leave me a message and I’ll get back to you as soon as possible. Thanks!