Skip to content

Instantly share code, notes, and snippets.

@himanshuahuja96
Last active December 12, 2020 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save himanshuahuja96/6f19732ec933dd1949bc2a758dde4ec9 to your computer and use it in GitHub Desktop.
Save himanshuahuja96/6f19732ec933dd1949bc2a758dde4ec9 to your computer and use it in GitHub Desktop.
<?php
//github plugin url: https://github.com/hissy/rs-csv-importer
//wp plugin directory url: http://wordpress.org/plugins/really-simple-csv-importer/
//add to your functions.php in current child theme or create a child theme using any plugin/website
function really_simple_csv_importer_save_meta_filter( $meta, $post, $is_update ) {
if( isset($meta['header_image']) ){
include_once( ABSPATH . 'wp-admin/includes/image.php' );
$imageurl = $meta['header_image'];
$imagetype = end(explode('/', getimagesize($imageurl)['mime']));
$uniq_name = date('dmY').''.(int) microtime(true);
$filename = $uniq_name.'.'.$imagetype;
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($imageurl);
$savefile = fopen($uploadfile, 'w');
fwrite($savefile, $contents);
fclose($savefile);
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
$imagenew = get_post( $attach_id );
$fullsizepath = get_attached_file( $imagenew->ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
wp_update_attachment_metadata( $attach_id, $attach_data );
$meta['header_image'] = $attach_id;
}
return $meta;
}
add_filter( 'really_simple_csv_importer_save_meta', 'really_simple_csv_importer_save_meta_filter', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment