Last active
May 16, 2021 01:29
-
-
Save allysonsouza/7a3fee06986ca20a0e784b2ccc568df0 to your computer and use it in GitHub Desktop.
Create a WordPress media from file path and attach it to a post.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Create media from path. | |
* | |
* @param string $file_path | |
*/ | |
function create_media_from_path( $file_path, $post_id = 0 ) { | |
// Requires | |
require_once( ABSPATH . 'wp-admin/includes/admin.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
// Upload media | |
$uploaded = wp_upload_bits( | |
basename( $file_path ), | |
null, | |
file_get_contents( $file_path ) | |
); | |
if ( isset( $upload['error'] ) && $upload['error'] ) { | |
return false; | |
} | |
// Attachment creation | |
// Provide a $post_id if you want to attach it | |
$filename = $uploaded['file']; | |
if ( $filename > '' && $post_id ) { | |
$wp_filetype = wp_check_filetype( basename( $filename ), null ); | |
$attachment = array( | |
'post_mime_type' => $wp_filetype['type'], | |
'post_title' => preg_replace('/\.[^.]+$/', '', basename( $filename ) ), | |
'post_content' => '', | |
'post_status' => 'inherit' | |
); | |
$attach_id = wp_insert_attachment( $attachment, $filename, $post_id ); | |
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename ); | |
wp_update_attachment_metadata( $attach_id, $attach_data ); | |
return $attach_id; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment