Many (ok probably most) WordPress websites use a great plugin called Yoast SEO. It really is a great one stop shop for all of your SEO needs. You might not use it to its full potential (we can help) but one setting that I highly suggest that everyone use is the Social/Facebook default image. It will ensure that when your posts get shared a decent image will be used.

For our clients we have started using a default branded image here and it has worked out great. So great in fact that I realized we should take advantage of this image in the theme code when there is no featured image supplied.

Now your theme might use WordPress’ functions a little different than we do but if you are using the_post_thumbnail() to show the featured image here is a little block of code that will fallback on the Yoast SEO default image if it is not supplied.

/* DEFAULT IMAGE FALLBACK */
// retrieves the attachment ID from the file URL
function artifakt_get_image_id($image_url) {
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
return $attachment[0];
}
add_filter( 'post_thumbnail_html', 'artifakt_post_thumbnail_fallback', 20, 5 );
function artifakt_post_thumbnail_fallback( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
if ( empty( $html ) ) {
// return you Yoast SEO default image if the post thumbnail html is empty
$opt = get_option('wpseo_social');
$url = $opt['og_default_image'];
if ( $id !== '' ) {
$id = artifakt_get_image_id($url);
return wp_get_attachment_image( $id, $size );
}
}
return $html;
}

There are two functions used. The first one finds an attachment’s ID based on the URL which we use in the second function if the thumbnail html is empty. That’s all there is! Now if a featured image is not assigned to a post, the Yoast SEO default OG:Image will be placed in it’s place (depending on where/how the theme uses it).

- Adam Graham, Development Team Lead

TELL US WHAT YOU THINK

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

LET'S TALK ABOUT HOW WE CAN HELP WITH YOUR NEXT DIGITAL STRATEGY PROJECT.