Skip to content

Instantly share code, notes, and snippets.

@jaredwilli
Created January 30, 2011 17:44
Show Gist options
  • Save jaredwilli/803048 to your computer and use it in GitHub Desktop.
Save jaredwilli/803048 to your computer and use it in GitHub Desktop.
<?php
function update_attachment() {
global $post;
wp_update_attachment_metadata( $post->ID, $_POST['a_image'] );
if( !empty( $_FILES['a_image']['name'] )) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
$override['action'] = 'editpost';
$file = wp_handle_upload( $_FILES['a_image'], $override );
if ( isset( $file['error'] )) {
return new WP_Error( 'upload_error', $file['error'] );
}
$file_type = wp_check_filetype($_FILES['a_image']['name'], array(
'jpg|jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
));
if( $file_type['type'] ) {
$name_parts = pathinfo( $file['file'] );
$name = $file['filename'];
$type = $file['type'];
$title = $_POST['a_title'] ? $_POST['a_title'] : $name;
$content = $_POST['a_desc'];
$post_id = $post->ID;
$attachment = array(
'post_title' => $title,
'post_type' => 'attachment',
'post_content' => $content,
'post_parent' => $post_id,
'post_mime_type' => $type,
'guid' => $file['url'],
);
foreach( get_intermediate_image_sizes() as $s ) {
$sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => true );
$sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
$sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
$sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
}
$sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
foreach( $sizes as $size => $size_data ) {
$resized = image_make_intermediate_size( $file['file'], $size_data['width'], $size_data['height'], $size_data['crop'] );
if ( $resized )
$metadata['sizes'][$size] = $resized;
}
$attach_id = wp_insert_attachment( $attachment, $file['file'] /*, $post_id - for post_thumbnails*/);
if ( !is_wp_error( $id )) {
$attach_meta = wp_generate_attachment_metadata( $attach_id, $file['file'] );
wp_update_attachment_metadata( $attach_id, $attach_meta );
}
update_post_meta( $post->ID, 'a_image', $images );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment