Return to Snippet

Revision: 41950
at February 25, 2011 06:26 by chrs


Initial Code
function set_featured_image($post_ID){

	if(!has_post_thumbnail($post_ID)){
		
		$args = array(
		    'post_parent'    => $post_ID,
		    'post_type'      => 'attachment',
		    'numberposts'    => 1,
		    'post_status'    => null,
		    'post_mime_type' => 'image',
		);
		
		if($image = get_children($args)) {
			$image = current($image);
			add_post_meta($post_ID, '_thumbnail_id', $image->ID);
		}
	}
}

add_action("publish_post", "set_featured_image");

Initial URL


Initial Description
If a post is published without setting a featured image and there is an image attachment, this will select an image from the media library and set it as the featured image.

Initial Title
Wordpress - Set featured image if nothing is selected

Initial Tags
wordpress

Initial Language
PHP