I am looking for a filter to define what image on a post sets the facebook OG image. In my case I have the image I want to use in a post meta field.

I have looked around but am unsure of the best way to handle this. Is there a core wordpress filter for this? If so I could not find one.

One solution that I looked into was through modifying the yoast seo plugin filters since we do have that plugin on our site. By default it looks to put the OG meta on the featured image which is not what I am looking for.

1
1

The wpseo_opengraph_image filter can only be used to modify the existing og:image. Otherwise, you will need to hook into the wpseo_opengraph action to add a different image.

Here’s an example of adding an image from a custom field on the post object (assuming you’re using ACF here).

function my_wpseo_opengraph() {
    global $post;

    if (isset($post)) {
        $og_image = get_field('your_field_name', $post->ID);
        if ($og_image) {
            $image_url = $og_image['sizes']['large'];
            $GLOBALS['wpseo_og']->image_output($image_url);
        }
    }
}

add_action('wpseo_opengraph', 'my_wpseo_opengraph', 29);

Leave a Reply

Your email address will not be published. Required fields are marked *