Snippet: Set Featured Image Automatically If no Featured Image is present

Add following snippet to “functions.php”

Snippet

add_action( 'save_post', 'set_featured_image_func' );
function set_featured_image_func() {

    if ( ! isset( $GLOBALS['post']->ID ) || has_post_thumbnail( get_the_ID() ) )
        return NULL;

    $args = array(
        'numberposts'    => 1,
        'order'          => 'ASC',
        'post_mime_type' => 'image',
        'post_parent'    => get_the_ID(),
        'post_status'    => NULL,
        'post_type'      => 'attachment'
    );

    $attached_image = get_children( $args );
    if ( $attached_image ) {
        foreach ( $attached_image as $attachment_id => $attachment )
            set_post_thumbnail( get_the_ID(), $attachment_id );
    }

}

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>