I am trying to set the Featured image as the og:image
I have tried various ways and plugins (Yoast) but finding it hard to get my head around this.
The issue is that it isn’t picking up the feature image at all instead it is picking up the images in the content.
This is my current pages code for the single blog post. This is the part which i need to be able to get when sharing the blog post to Facebook rather then the content images.
<div class="image-wrapper">
<?php if( get_field('featured_image') ): ?>
<?php $featuredImage = get_field('featured_image'); ?>
<img rel="image_src" src="https://wordpress.stackexchange.com/questions/159162/<?php echo $featuredImage["url']; ?>" alt="">
<?php else: ?>
<img src="https://lorempixel.com/842/458/?rand9" alt="">
<?php endif; ?>
</div>
It does do this weird thing when a blog post hasn’t got any images in the content it then picks up the feature images and images in the sidebar. I also ran the Facebook debugger but again it is only picking up the contents imagery.
I did find this snippet that targets the featured image but i have a feeling because mine is a custom post it may not be picking it up.
<meta property="og:image" content="<?php $post_thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'large'); echo $post_thumbnail[0]; ?>" />
Any suggestions would be great. If you need anything else, let me know.
2 Answers
It appears that your site doesn’t use the core WordPress Featured Image feature but instead uses a custom image field (probably from Advanced Custom Fields). Yoast’s plugin, Jetpack, and presumably many others look for the Featured Image image when setting the opengraph meta tag. So you have two options:
- Use the core Featured Image feature with one of the plugins that adds the featured image to an opengraph meta tag
- Change your meta property to use the ACF field:
<meta property="og:image" content="<?php $featuredImage = get_field('featured_image'); echo esc_url( $featuredImage['url'] ); ?>" />
Aside: if your featured image (however it’s implemented) has any meaning and is not “purely decorative,” make sure your site supports a way to give it appropriate alt text for accessibility.