
Its easy to forget to set a featured image when creating a new post or page, and honestly, it may not seem terribly important. But it can be a good idea to make sure this image is always set if you use the featured image in post lists for your theme. More importantly, SEO plugins or themes may need the featured image for rich snippets or Facebook open graph meta tags.
Not providing a rich snippet or meta tag for an image, can create problems when your website visitor tries to share the page or post on Google Plus or Facebook. Without this signal, Google or Facebook will use their own algorithms to determine which image on your page will be used to represent your page. And often, that is the first image on the page. If that is a small logo, that would get scaled up into a pixelated image, which would not represent the website well.
Automatically setting a featured image can be easily done in the theme. Simply hook onto the "save post" action, and check if a thumbnail has been set. If not, search the content for an image, and set the featured image to that image. That way, if the user forgets to set the featured image, the theme automatically sets it to the first image it finds in the content. If the user does set a featured image, it won't get over-written.
function st_save_post($post_id) {
if (!defined('DOING_AUTOSAVE')||!DOING_AUTOSAVE) { // skip if autosave
if (!($id=wp_is_post_revision($post_id)))
$id=$post_id;
if (isset($_POST['content'])&&!get_post_thumbnail_id($id)) { // set featured image
$match=array();
preg_match('/"[^"]*wp\-image\-(\d+)/',$_POST['content'],$match);
if (isset($match[1])) set_post_thumbnail($post_id,intval($match[1]));
}
}
}
add_action('save_post','st_save_post');
The only tricky part about this is working with the WordPress post revision system. If you attempt to get the post thumbnail using $post_id, which could be a revision post ID, WordPress may report that no thumbnail is set, even if the parent post has a thumbnail set. So we need to lookup the parent post ID, if exists, using wp_is_post_revision.
Adding this little bit of functionality to a theme, makes setting featured images one less thing your customers have to worry about, without intruding on their ability to set the featured image as they see fit.
3 comments
Comments are closed.