Setting a featured image to a post in WordPress is a great way to make your posts stand out and grab the attention of readers. It can also help you create a consistent look and feel for your blog or website. Fortunately, there are several ways to set featured images to posts automatically in WordPress.
A way to set featured images to posts automatically is to use a custom script. This requires some coding knowledge, but it can be a great way to automate the process. If you are finding a solution to set featured images automatically in WordPress, the following code lines will help you save several minutes.
The action below only supports setting featured images on updating a post. The function first checks if a post already has a featured image. If not, it queries all images uploaded to the post and set the first uploaded image as the featured one.
function my_plugin_set_feature($post_id) { if (!has_post_thumbnail($post_id)) { $attached_images = get_children("post_parent=$post_id&post_type=attachment&post_mime_type=image&numberposts=1" ); if ($attached_images) { foreach ($attached_images as $attachment_id => $attachment) { set_post_thumbnail($post_id, $attachment_id); break; } } } } add_action('save_post', 'my_plugin_set_feature');