may it will help you:
public static function upload_image_as_term_thumbnail( $term_id, $img_base64Str ){
global $blog_id, $wpdb;
if(!empty($img_base64Str)) {
list($type, $img_base64Str) = explode(';', $img_base64Str);
list(, $type) = explode(':', $type);
list(, $type) = explode('/', $type);
list(, $img_base64Str) = explode(',', $img_base64Str);
$type = strtolower($type);
$img = base64_decode($img_base64Str);
/*
wp_upload_dir( null, false );
*/
$wp_upload_dir = wp_upload_dir();
$filename = "term_thumbnail_".time().".$type";
$path_to_file = $wp_upload_dir['path']."/".$filename;
$filetype = wp_check_filetype( basename( $filename), null );
if( !function_exists( 'wp_handle_upload' ) ){
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
}
@file_put_contents( $path_to_file, $img );
$attachment = array(
'post_author' => 1,
'post_content' => '',
'post_content_filtered' => '',
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_excerpt' => '',
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => $filetype['type'],
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_password' => '',
'to_ping' => '',
'pinged' => '',
'post_parent' => 0,
'menu_order' => 0,
'guid' => $wp_upload_dir['url'].'/'.$filename,
);
$wpdb->insert("{$wpdb->prefix}posts", $attachment);
$attach_id = $wpdb->insert_id;
if($attach_id == false){
return false;
}
$attach_data = wp_generate_attachment_metadata( $attach_id, $path_to_file );
wp_update_attachment_metadata( $attach_id, $attach_data );
update_attached_file($attach_id, $path_to_file);
self::set_term_thumbnail( $term_id, $thumbnail_id );
/*
or you may need the image URL
*/
return $attach_id;
}
return false;
}
-
This reply was modified 7 years, 5 months ago by suifengtec.