Skip to content

Instantly share code, notes, and snippets.

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 allysonsouza/7a3fee06986ca20a0e784b2ccc568df0 to your computer and use it in GitHub Desktop.
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.
<?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