The problem got fixed by adding the following code to the functions.php:
function set_featured_image_as_social_and_og_image() {
if (is_single() || is_page()) {
global $post;
// Check if the post has a featured image
if (has_post_thumbnail($post->ID)) {
$featured_image_url = get_the_post_thumbnail_url($post->ID, 'full');
// Set the featured image as the social image for Yoast SEO
update_post_meta($post->ID, '_yoast_wpseo_opengraph-image', $featured_image_url);
update_post_meta($post->ID, '_yoast_wpseo_twitter-image', $featured_image_url);
// Add Open Graph tags if they don't exist
add_action('wp_head', function() use ($post, $featured_image_url) {
global $wp_filter;
// Check if Yoast SEO is adding the og:image tag
$yoast_exists = false;
if (isset($wp_filter['wpseo_opengraph'])) {
foreach ($wp_filter['wpseo_opengraph']->callbacks as $priority => $functions) {
foreach ($functions as $function) {
if (strpos($function['function'][1], 'og_image') !== false) {
$yoast_exists = true;
break 2;
}
}
}
}
// Add Open Graph tags if Yoast SEO is not adding them
if (!$yoast_exists) {
$title = get_the_title($post->ID);
$description = get_the_excerpt($post->ID);
$url = get_permalink($post->ID);
echo '<meta property="og:title" content="' . esc_attr($title) . '">' . "\n";
echo '<meta property="og:description" content="' . esc_attr($description) . '">' . "\n";
echo '<meta property="og:url" content="' . esc_url($url) . '">' . "\n";
echo '<meta property="og:image" content="' . esc_url($featured_image_url) . '">' . "\n";
echo '<meta property="og:type" content="article">' . "\n";
}
}, 5);
}
}
}
add_action(‘wp’, ‘set_featured_image_as_social_and_og_image’);