Return to Snippet

Revision: 60425
at November 7, 2012 20:12 by krike


Initial Code
/**
* Function to upload an image to the media library and set it as the featured image of a post
* @param string Name of the upload field
* @param int ID of the post
* @return string
* */
public function set_featured_image($file, $post_id){
    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');
    $attachment_id = media_handle_upload($file, $post_id);
    update_post_meta($post_id, '_thumbnail_id', $attachment_id);
    $attachment_data = array(
    'ID' => $attachment_id
    );
    wp_update_post($attachment_data);
    return $attachment_id;
}

Initial URL
https://github.com/krike/WPelements

Initial Description
A function to upload an image to the media library and set it as featured image of a post. It requires 2 params. The name of the upload field and of course the post ID.

This function is part of the WPelements library class available on Github. Feedback / suggestions / improvements are always welcome.

Initial Title
Wordpress function to upload image and set as featured image

Initial Tags
class, php, image, wordpress

Initial Language
PHP