Reputation: 71
Here, I am attaching the image to post (custom field) by using wp_insert_attachment function but unfortunately i am not getting the attachment id from wp_inset_attachment function. Here is my code.
function jda_upload_image( $file = array() ) {
require_once( ABSPATH . 'wp-admin/includes/admin.php' );
$file_return = wp_handle_upload( $file, array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment( $attachment, $file_return['url']);
/* Here I am not getting the attachment_id */
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
Upvotes: 1
Views: 702
Reputation: 64
It took time. I tried with your code but got stuck. So I did that with the following code. It works fine for me. Perhaps works for you as well.
Change the code as per your requirement.
$file = $_FILES['logo'];
if(!empty($file)) {
handle_logo_upload($file);
}
function handle_logo_upload($file){
if ( !function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
require_once ( ABSPATH . 'wp-admin/includes/image.php' );
$uploadedfile = $file;
$upload_overrides = array(
'test_form' => false,
);
if(!empty($uploadedfile['name'])) {
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile ) {
$wp_filetype = $movefile['type'];
$filename = $movefile['file'];
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename);
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
echo '<br>';
var_dump($uploadedfile);
return "pass";
}
}
return "fail";
}
Upvotes: 1