public function AddImage($file, $post_id,$desc = null){ require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); $file = "http://".$file; if ( ! empty( $file ) ) { // Set variables for storage, fix file filename for query strings. preg_match( '/[^?]+.(jpe?g|jpe|gif|png)b/i', $file, $matches ); if ( ! $matches ) { return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL' ) ); } $file_array = array(); $file_array['name'] = basename( $matches[0] ); // Download file to temp location. $file_array['tmp_name'] = download_url( $file ); // If error storing temporarily, return the error. if ( is_wp_error( $file_array['tmp_name'] ) ) { return $file_array['tmp_name']; } // Do the validation and storage stuff. $id = media_handle_sideload( $file_array, $post_id, $desc ); // If error storing permanently, unlink. if ( is_wp_error( $id ) ) { @unlink( $file_array['tmp_name'] ); return $id; } set_post_thumbnail($post_id, $id); } }
$file is source URL of the image. Remove http:// from the URL before sending. for e.g google.com/apple.jpg not http://google.com/apple.jpg. You can add www. but not http://. $post_id is the id of the post you want to update. call this function from anywhere with postid and image url
Leave a Reply