WordPress Snippets at WPcustoms

Set first image as featured image

grabs the first image in your body content and sets it as the post’s featured image.


/**
 * Snippet Name: Set first image as featured image
 * Snippet URL: https://wpcustoms.net/snippets/set-first-image-featured-image/
 */
  function set_featured_image_from_attachment($content) {
	global $post;
	if (has_post_thumbnail()) {
		// display the featured image
		$content = the_post_thumbnail() . $content;
	} else {
		// get & set the featured image
		$attachments = get_children(array(
			'post_parent' => $post->ID, 
			'post_status' => 'inherit', 
			'post_type' => 'attachment', 
			'post_mime_type' => 'image', 
			'order' => 'ASC', 
			'orderby' => 'menu_order'
		));
		if ($attachments) {
			foreach ($attachments as $attachment) {
				set_post_thumbnail($post->ID, $attachment->ID);
				break;
			}
			// display the featured image
			$content = the_post_thumbnail() . $content;
		}
	}
	return $content;
}
add_filter('the_content', 'set_featured_image_from_attachment');