Wordpress-seo: Use og:image:width and og:image:height Open Graph tags to render image on first Facebook like/share action

Created on 19 Mar 2015  Â·  65Comments  Â·  Source: Yoast/wordpress-seo

When content is shared for the first time, the Facebook crawler will scrape and cache the metadata from the URL shared. The crawler has to see an image at least once before it can be rendered. This means that the first person who shares a piece of content won't see a rendered image.

To solve this, use og:image:width and og:image:height Open Graph tags
Using these tags will specify the image to the crawler so that it can render it immediately without having to asynchronously.

As taken from:
https://developers.facebook.com/docs/sharing/best-practices#images

social support feature request

Most helpful comment

+1 for this. It's real issue for my wp editors. They must add daily multiple WP posts to the FB, so i created a temporary fix for this, you just need to add it somewhere in functions.php

/**
 * Temporary fix
 * OpenGraph add a og:image:width and og:image:height for FB async load of og:image issues
 *
 * https://github.com/Yoast/wordpress-seo/issues/2151
*  https://developers.facebook.com/docs/sharing/webmasters/optimizing#cachingimages
 */
if(class_exists('WPSEO_OpenGraph_Image')) {
    add_filter("wpseo_opengraph", function () {
        global $wpseo_og;

        // will get a array with images
        $opengraph_images = new WPSEO_OpenGraph_Image( $wpseo_og->options );

        foreach ( $opengraph_images->get_images() as $img ) {
            // this block of code will first convert url of image to local path
            // for faster process of image sizes later
            $upload_dir = wp_upload_dir();
            $img_src = str_replace($upload_dir['url'], $upload_dir['path'], $img);
            $size = getimagesize($img_src);

            // display of this tags with Yoast SEO plugin
            $wpseo_og->og_tag( 'og:image:width', $size[0] );
            $wpseo_og->og_tag( 'og:image:height', $size[1] );
        }

    }, 32);
}

All 65 comments

+1. This would be a great addition!

If any other devs are looking for a quick solution in the meantime: https://github.com/synapticism/ubik-seo/blob/master/ubik-seo/ubik-seo-yoast.php

+1 this would also solve some problems with Facebook not recognizing the image properly

+1 here, currently struggling with this. My page is dynamically generated and the images are hosted elsewhere. I'm currently using the "wpseo_opengraph_image" filter and would love for it to either generate the dimensions, or allow me to enter them.

+1 will submit sample code

    private function get_featured_image( $post_id ) {
        if ( function_exists( 'has_post_thumbnail' ) && has_post_thumbnail( $post_id ) ) {
            /**
             * Filter: 'wpseo_opengraph_image_size' - Allow changing the image size used for OpenGraph sharing
             *
             * @api string $unsigned Size string
             */
            $thumb = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), apply_filters( 'wpseo_opengraph_image_size', 'original' ) );

            if ( $this->check_featured_image_size( $thumb ) ) {
                // return $this->add_image( $thumb[0] );
                array_push( $this->images, $thumb );
            }
        }
    }

    public function image( $image = false ) {
        $opengraph_images = new WPSEO_OpenGraph_Image( $this->options, $image );

        foreach ( $opengraph_images->get_images() as $img ) {
            if(is_array($img)){
                $this->og_tag( 'og:image', esc_url( $img[0] ) );
                $this->og_tag( 'og:image:width', $img[1] );
                $this->og_tag( 'og:image:height', $img[2] );
            } else {
                $this->og_tag( 'og:image', esc_url( $img ) );
            }
        }
    }

+1 for this. It's real issue for my wp editors. They must add daily multiple WP posts to the FB, so i created a temporary fix for this, you just need to add it somewhere in functions.php

/**
 * Temporary fix
 * OpenGraph add a og:image:width and og:image:height for FB async load of og:image issues
 *
 * https://github.com/Yoast/wordpress-seo/issues/2151
*  https://developers.facebook.com/docs/sharing/webmasters/optimizing#cachingimages
 */
if(class_exists('WPSEO_OpenGraph_Image')) {
    add_filter("wpseo_opengraph", function () {
        global $wpseo_og;

        // will get a array with images
        $opengraph_images = new WPSEO_OpenGraph_Image( $wpseo_og->options );

        foreach ( $opengraph_images->get_images() as $img ) {
            // this block of code will first convert url of image to local path
            // for faster process of image sizes later
            $upload_dir = wp_upload_dir();
            $img_src = str_replace($upload_dir['url'], $upload_dir['path'], $img);
            $size = getimagesize($img_src);

            // display of this tags with Yoast SEO plugin
            $wpseo_og->og_tag( 'og:image:width', $size[0] );
            $wpseo_og->og_tag( 'og:image:height', $size[1] );
        }

    }, 32);
}

The above code gave me an unexpected function error so based on @PayteR 's code this is what worked for me.

/**
 * Temporary fix
 * OpenGraph add a og:image:width and og:image:height for FB async load of og:image issues
 *
 * https://github.com/Yoast/wordpress-seo/issues/2151
*  https://developers.facebook.com/docs/sharing/webmasters/optimizing#cachingimages
 */
function WPSEO_OpenGraph_Image() {
  global $wpseo_og;

  // will get a array with images
  $opengraph_images = new WPSEO_OpenGraph_Image( $wpseo_og->options );

  foreach ( $opengraph_images->get_images() as $img ) {
    // this block of code will first convert url of image to local path
    // for faster process of image sizes later
    $upload_dir = wp_upload_dir();
    $img_src = str_replace($upload_dir['url'], $upload_dir['path'], $img);
    $size = getimagesize($img_src);

    // display of this tags with Yoast SEO plugin
    $wpseo_og->og_tag( 'og:image:width', $size[0] );
    $wpseo_og->og_tag( 'og:image:height', $size[1] );
  }

}
if(class_exists('WPSEO_OpenGraph_Image')) {
  add_filter("wpseo_opengraph", "WPSEO_OpenGraph_Image");
} 

ah yes, it will not work on older PHP versions than 5.3 because of anonymous function

:+1: Correct!

+1

+1 for this.

+1
Experiencing this issue now, and can't actually scrape for the new image until I add the sizes.

+1, same here ! Could be great to add it to the plugin ;) !

I have opened PR to do this automatically for featured images.

Doing it for other cases is a little problematic to accomplish _reliably_, reversing URLs sucks. Saving it for later. :)

I am using the above code on coast-classics.com.

If you take a look at the page source; it writes the og:width and og:height twice.

Somehow the above code is duplicating it. I thought yoast might have implemented it so I removed the code, but then both of the sets of og:widht & od:height disappeared.

Could this affect negatively and how could I avoid this duplication.

@MarcusFuto This is now partially implemented in the plugin (for the case when featured image is used since it's easy to determine dimensions for). I am not sure how third party snippets interact with that.

Thanks @Rarst.

Like I said. The snippet was removed, but then no image width or height was displayed in the code at all.

If I understand correctly, they should actually be there when I remove the snippet?

Thanks!

In the case that featured image is used — yes.

Then that is very strange. It is mainly my products that I want to be possible to share. and all of those have the specs. Do you think that me having put in that code could have duplicated the image width and height? Could you give an example how it is supposed to look like in the page source when yoast is actually working?
see an example of mine: view-source:http://www.coast-classics.com/product/hasta-de-la-muerte

THanks! :8ball:

Do you think that me having put in that code could have duplicated the image width and height?

Well, yes, if plugin outputs one set and you add a code that outputs one more set then it's duplicate.

Could you give an example how it is supposed to look like in the page source when yoast is actually working?

That looks about right (sans duplicate issue). The dimensions set right after image itself is produced by the plugin, or so I would guess from how it is processed in the code.

please have a look when I remove the code above from my functions file:
view-source:http://www.coast-classics.com/product/test
Tell me when you've seen it.
Anyway, do you think the duplication is an issue?

It's really hard to tell what the issue is from looking at results. What is that image URL? Is post thumbnail / featured image definitely being used for it?

Well I must say, I am not sure at all. Everything within there as you saw it should be from the yoast plugin. I don't really know what you are referring to with that. In all products a featured image plus gallery images have been set. That I am sure of.

Is this specific image (showing up in page source) in this specific post the one set as featured or not?

yes

Then I have no idea why plugin doesn't pick up its dimensions out of the box. Do you run the latest stable plugin version?

Yes I do.

I have the same issue: featured images are being used but the og:img:width and height are not set.

Or is this change not yet available in the Pro version of the plugin?

The Premium plugin features should be in sync with what is released in Free version.

$img_src = str_replace($upload_dir['url'], $upload_dir['path'], $img);
must be changed to
$img_src = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $img);
wp_upload_dir() return current upload dir, that changed every month

+1 for this!

+1 this is not working, Facebook does not show our shared posts with images. We have to manually import it using the Facebook debugger.

+1, it doesn't work on a all sites I own, all up to date.

Hello friends ..
Im newbies for webdevelopment..I use this line of code in my share button but its not show sharing thumbnail...

i precache my "article link&image" use this link "https://developers.facebook.com/tools/debug/" .. i dont like to copy&paste the article link at pre cache every time.. that make waste of time.. can anyone help me.. automatic page render and share content is available??

I'm surprised this is still a problem, since this plugin does get updated regularly.

@avantegarde your solution works great, except it doesn't add dimensions for the image if a featured image is not set and the default opengraph image from SEO > Social > Facebook > Image URL: is being used.

The problem here is that we don't verify that images are local and thus getting image size is not reliable. We need to solve this differently, but we'll pick it up for a 3.4 release.

Thanks Joost!

After update to 3.4 this code becomes obsolete and don't work anymore... When we use this, the og image sizes tags (og:image:width and og:image:height) becomes duplicated when post has no Facebook Image set in Yoast meta box...

@gpmr84 I don't follow, if something got broken in recent release please open a new issue with details.

still working thanks

+1 This is required if we wish LinkedIn to use the Open Graph image when sharing a page.

If width/height are not specified, LinkedIn will ignore the Open Graph image and use the first image from the post body. LinkedIn will also ignore the featured image in this scenario as the width/height attributes for the featured image won't be set when a custom Open Graph image is specified.

Please inform the customer of conversation # 180446 when this conversation has been closed.

Please inform the customer of conversation # 184718 when this conversation has been closed.

Please inform the customer of conversation #184767 when this conversation has been closed.

Please inform the customer of conversation # 185083 when this conversation has been closed.

Please inform the customer of conversation # 189972 when this conversation has been closed.

Please inform the customer of conversation # 190308 when this conversation has been closed.

Please inform the customer of conversation # 192238 when this conversation has been closed.

Please inform the customer of conversation # 193125 when this conversation has been closed.

Please inform the customer of conversation # 191158 when this conversation has been closed.

User 192238 reports that an All In One WP Security setting was preventing the page from appearing in LinkedIn as expected.

Please inform the customer of conversation # 196023 when this conversation has been closed.

Please inform the customer of conversation # 197492 when this conversation has been closed.

Please inform the customer of conversation # 203504 when this conversation has been closed.

Please inform the customer of conversation # 215823 when this conversation has been closed.

Please add optional width/height/<any-attr> parameters to the add_image() function of class-opengraph.php
Without this, the wpseo_add_opengraph_images action is less usable since one can not provide additional custom images with their dimension (since add_image() just accept the URL string).

thank you

I've been testing this and I think this is no longer an issue. I've shared posts on LinkedIn without the og:image:width and og:image:height tag and the image is showing correctly.

@rmarcano You're correct. Also tested with Facebook. Closing this as this is no longer an issue.

It still is, tho, see attached notice in the Facebook Sharing Debugger tool:

image

@timocouckuyt This only happens the first time you check a page (because the images are processed asynchronously, they can't always be processed before the result is displayed). It should not happen the second time you test check the same page.

@Rudloff I know, but still, the dimensions aren't there :-)

A fix for this is in progress: https://github.com/Yoast/wordpress-seo/pull/9418

Hi i done the issue as per the above solution like -----

$thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');
echo '';
echo '';
echo '';

then we get the particular image width and height, in the og:image:width & og:image:height respectively but yet i can't able to get the edited post like title or description or image. its quite sad.

The only solution is past the url of page to the below facebook debug service

https://developers.facebook.com/tools/debug/

I want its like dynamic ie i get the post when i put the 1st time. But i need when i edit the same post it must reflect what ever the title or description or image to 2nd time, when i am going to sharing the same post to the facebook

+1 for this. It's real issue for my wp editors. They must add daily multiple WP posts to the FB, so i created a temporary fix for this, you just need to add it somewhere in functions.php

/**
 * Temporary fix
 * OpenGraph add a og:image:width and og:image:height for FB async load of og:image issues
 *
 * https://github.com/Yoast/wordpress-seo/issues/2151
*  https://developers.facebook.com/docs/sharing/webmasters/optimizing#cachingimages
 */
if(class_exists('WPSEO_OpenGraph_Image')) {
    add_filter("wpseo_opengraph", function () {
        global $wpseo_og;

        // will get a array with images
        $opengraph_images = new WPSEO_OpenGraph_Image( $wpseo_og->options );

        foreach ( $opengraph_images->get_images() as $img ) {
            // this block of code will first convert url of image to local path
            // for faster process of image sizes later
            $upload_dir = wp_upload_dir();
            $img_src = str_replace($upload_dir['url'], $upload_dir['path'], $img);
            $size = getimagesize($img_src);

            // display of this tags with Yoast SEO plugin
            $wpseo_og->og_tag( 'og:image:width', $size[0] );
            $wpseo_og->og_tag( 'og:image:height', $size[1] );
        }

    }, 32);
}

This worked for me with a small modification - it seems the $img_src is an array, and its "url" key holds the URL string ($img_src["url"]). So the code that worked for me goes like this:

/**
 * Temporary fix
 * OpenGraph add a og:image:width and og:image:height for FB async load of og:image issues
 *
 * https://github.com/Yoast/wordpress-seo/issues/2151
*  https://developers.facebook.com/docs/sharing/webmasters/optimizing#cachingimages
 */

if(class_exists('WPSEO_OpenGraph_Image')) {
    add_filter("wpseo_opengraph", function () {
        global $wpseo_og;

        // will get a array with images
        $opengraph_images = new WPSEO_OpenGraph_Image( $wpseo_og->options );

        foreach ( $opengraph_images->get_images() as $img ) {
            // this block of code will first convert url of image to local path
            // for faster process of image sizes later
            $upload_dir = wp_upload_dir();
            $img_src = str_replace($upload_dir['url'], $upload_dir['path'], $img);
            $size = getimagesize($img_src["url"]);

            // display of this tags with Yoast SEO plugin
            $wpseo_og->og_tag( 'og:image:width', $size[0] );
            $wpseo_og->og_tag( 'og:image:height', $size[1] );
        }

    }, 32);
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

qmdev picture qmdev  Â·  6Comments

theRealRizeo picture theRealRizeo  Â·  5Comments

danieltj27 picture danieltj27  Â·  6Comments

Pcosta88 picture Pcosta88  Â·  6Comments

cristopherrosenberg picture cristopherrosenberg  Â·  3Comments