Get facebook to show a default thumbnail for your Wordpress site, or a specific ‘featured’ image on post pages.

So because I’m lazy, for a really long time I’ve left facebook “attempt” to guess what image to use for my facebook shared links. Sadly facebook either gives me my twitter bird, or my white transparent logo (displayed on a white background of course…), despite having other images in my posts. So I’ve quickly hacked together this little script you can throw in your theme’s function file.

Basically, in the function – set your site’s default image location (I use my CDN because I’m awesome), guess if we’re using http or https – and if we’re on a singluar/post page – check for a featured image (you pick featured image when uploading or inserting the image into the actual post from the backend) and go from there.

Put this in your Theme’s functions.php file. You should only need to edit the default image URL – highlighted so you can see it.

add_action( 'wp_head', 'insert_image_src_rel_in_head', 5 );
function insert_image_src_rel_in_head()
{
    global $post;

    // Default thumbnail for facebook share.
    // You can either use a full link (http://darrennolan.com/some_image.png) or use CDN style.
    $image_url = "//cdn.darrennolan.com/dn-square.png";

    // If the post is singular, and has a "featured" gallery image - use it as the facebook thumbnail.
    if ( is_singular()) {
        if(has_post_thumbnail( $post->ID )) {
            $thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' );
            $image_url = esc_attr( $thumbnail_src[0] );
        }
    }

    // As facebook is stupid, and doesn't like links without protocol, quickly guess it if we need to and throw it into the image src to use.
    if (substr($image_url, 0, 2) == '//') {
        if (isset($_SERVER['HTTPS'])) {
            $image_url = 'https:' . $image_url;
        } else {
            $image_url = 'http:' . $image_url;
        }
    }

    echo '<meta property="og:image" content="' . $image_url . '"/>' . "\n";
}

Couple of gotcha’s. Facebook caches it’s thumbnail lookups when you put your site’s link into facebook. So for testing purposes, you need to do something like https://darrennolan.com?v=1 where v=1 keeps incrementing each time you update your theme/images/functions. Sadly that doesn’t always work because facebook isn’t completely stupid.