uploads – Import media files to WordPress from external API
Question
I am trying to upload media files to WordPress from an external API provider.
I have written a few codes, but it’s not importing anything.
I have no idea what is going wrong.
My codes are:
function import_external_media() {
// Set API endpoint URL, using local instance for now
$api_url="http://localhost/media";
// Fetch media data from API
$response = wp_remote_get( $api_url );
if ( is_wp_error( $response ) ) {
// Handle error
return;
}
$media_data = json_decode( wp_remote_retrieve_body( $response ), true );
// Set target directory for media files
$upload_dir = wp_upload_dir();
$target_dir = $upload_dir['basedir'] . '/external-media/';
// Create target directory if it doesn't exist
if ( ! file_exists( $target_dir ) ) {
mkdir( $target_dir, 0755, true );
}
// Import media files
foreach ( $media_data as $media ) {
$media_url = $media['url'];
$media_name = basename( $media_url );
$target_path = $target_dir . $media_name;
// Check if file already exists
if ( file_exists( $target_path ) ) {
continue;
}
// Fetch media file from URL
$file_data = wp_remote_get( $media_url );
if ( is_wp_error( $file_data ) ) {
// Handle error
continue;
}
// Save media file to target directory
$saved = file_put_contents( $target_path, wp_remote_retrieve_body( $file_data ) );
if ( $saved === false ) {
// Handle error
continue;
}
// Add media file to media library
$attachment = array(
'guid' => $upload_dir['baseurl'] . '/external-media/' . $media_name,
'post_mime_type' => $media['mime_type'],
'post_title' => $media['title'],
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $target_path );
// Generate metadata for attachment
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $target_path );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
}
}
// Hook into WordPress cron system to run import on schedule
add_action( 'wp_scheduled_event', 'import_external_media' );
My json structure is:
"fields": {
"title": "Playsam Streamliner",
"file": {
"fileName": "ladybug-7877480_960_720.jpg",
"contentType": "image/jpg",
"details": {
"image": {
"width": 600,
"height": 446
},
"size": 27187
},
"url": "https://cdn.pixabay.com/photo/2023/03/26/03/12/ladybug-7877480_960_720.jpg"
}
}
0
2 months
2023-03-31T00:18:54-05:00
2023-03-31T00:18:54-05:00 0 Answers
0 views
0
Leave an answer