Last active
April 23, 2021 10:14
-
-
Save vincentorback/98813ae4008081b6b9cbed890c683b2c to your computer and use it in GitHub Desktop.
Use ACF images combined with Yoast SEO default image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Remove default output of og:image from yoast | |
*/ | |
add_filter('wpseo_frontend_presenter_classes', function ($filter) { | |
$presenter_to_remove = [ | |
'Yoast\WP\SEO\Presenters\Open_Graph\Image_Presenter' | |
]; | |
foreach ($presenter_to_remove as $presenter) { | |
if (($key = array_search($presenter, $filter)) !== false) { | |
unset($filter[$key]); | |
} | |
} | |
return $filter; | |
}); | |
/** | |
* Use images from ACF field as og:images | |
*/ | |
function acf_images_as_og () { | |
global $post; | |
if (!$post) { | |
return; | |
} | |
$images = get_field('images', $post->ID); | |
if ($images) { | |
foreach ($images as $image_id) { | |
$image = wp_get_attachment_image_src($image, 'large'); | |
if (isset($image[0])) { | |
echo "<meta property=\"og:image\" content=\"" . $image[0] . "\">\n"; | |
} | |
} | |
} | |
// If Yoast SEO is installed, use that image as default aswell. | |
if (class_exists('WPSEO_Options', false)) { | |
$default_image = WPSEO_Options::get('og_default_image'); | |
if ($default_image) { | |
echo "<meta property=\"og:image\" content=\"" . $default_image . "\">\n"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment