Retrieve a value from Yoast SEO to use to set a default twitter card image honoring overrides

Here’s how I fixed it. If you paste this code in your theme’s functions.php, it will use the image set for Facebook also for Twitter if no image is set for Twitter.

If there is not image set for both Facebook and Twitter, it falls back to the default Facebook image in the Yoast settings (unfortunately, you can’t provide a default Twitter image there, so we’ll be using the Facebook one).

  // Add Twitter image to every page /article if none is defined

add_filter('wpseo_twitter_image', 'change_twitter_image');

function change_twitter_image($image) {

    if (!$image) {

        global $post;
        
        if (!$image = get_post_meta($post->ID)["_yoast_wpseo_opengraph-image"][0]) {
            $image = get_option("wpseo_social")["og_default_image"];
        }

    }
 
    return $image; 
  
};