cedcommerce
Unfortunately, that did not work.
Below is the complete code that I have.
It is actually function in a custom plugin that I created.
What it does is it is migrating files from an old system.
Like I said, it works for images but not for audio or video files.
The problem is it does not insert records in wp_postmeta.
function migrate_old_site_media($old_site_file_folder, $old_site_file_name){
require_once(ABSPATH . 'wp-load.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$artDir = 'wp-content/uploads/importedmedia/';
$siteurl = get_option('siteurl');
//if the directory doesn't exist, create it
if(!file_exists(ABSPATH.$artDir)) {
mkdir(ABSPATH.$artDir);
}
list($system_protocol, $system_folder_name) = explode($_SERVER['SERVER_NAME'], $siteurl);
$old_site_orig_file_abspath = str_replace($system_folder_name, "", ABSPATH) . $old_site_file_folder . '/' . $old_site_file_name;
$file_info = getimagesize($old_site_orig_file_abspath);
//create an array of attachment data to insert into wp_posts table
$artdata = array();
$artdata = array(
'post_author' => 1,
'post_date' => current_time('mysql'),
'post_date_gmt' => current_time('mysql'),
'post_title' => $old_site_file_name,
'post_status' => 'inherit',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_name' => sanitize_title_with_dashes(str_replace("_", "-", $old_site_file_name)), 'post_modified' => current_time('mysql'),
'post_modified_gmt' => current_time('mysql'),
'post_type' => 'attachment',
'guid' => $siteurl . $artDir . $old_site_file_name,
'post_mime_type' => $file_info['mime'],
'post_excerpt' => '',
'post_content' => ''
);
$uploads = wp_upload_dir();
$old_site_migrated_to_system_path = $uploads['basedir'] . '/importedmedia/' . $old_site_file_name;
//Copy original old_site file to WP uploads path.
rename($old_site_orig_file_abspath, ABSPATH . $artDir . $old_site_file_name);
$attach_id = wp_insert_attachment( $artdata, $old_site_migrated_to_system_path);
//generate metadata and thumbnails then delete original old_site file
if ($attach_data = wp_generate_attachment_metadata( $attach_id, $old_site_migrated_to_system_path)) {
wp_update_attachment_metadata($attach_id, $attach_data);
}
}