items as $item ) {
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
// Get the id for the current wp post
$post_ID = get_the_ID();
// Get the image data and store as a file, then upload
$image_data = file_get_contents( $item->raw );
$file = $wp_upload_dir[ 'basedir' ] . '/' . $item->filename;
file_put_contents( $file, $image_data );
$wp_filetype = wp_check_filetype( $item->filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype[ 'type' ],
'post_title' => sanitize_file_name( $item->filename ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file, $post_ID );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_ID, $attach_id );
}
//generate json for the gallery
$json_file = generate_gallery_json( $art_array );
//import json template to Elementor library
$import_result = elementor_library_import( $json_file, true );
//result
if ( $import_result == "failure" ) {
//if the import function fails, display an error
return display_error( 'The AI did not respond as expected. Check your prompt to make sure it is not too vague or confusingly worded.' );
} else {
//if successful, render the saved gallery in the Elementor page builder and refresh the view
return render_supstring_gallery( get_latest_element_id() );
}
} else {
//return null if user's prompt is empty
return false;
}
}
//Generates the Elementor json that can be imported to the library
function generate_gallery_json( $art_array ) {
//loop through the AI's response and output each image item
$art_loop_json = "";
foreach ( $art_array->items as $item ) {
$art_loop_json .= '
{
"id":' . $item->image_id . '
"url": "' . $item->image_url . '"
},
';
}
//assemble the final gallery json
$gallery_json = '
[{
"id": "' . gallery_id() . '",
"settings": {
"gallery": ['
. $art_loop_json .
'],
},
"elements": [],
"isInner": false,
"widgetType": "gallery",
"elType": "widget"
}]
';
//Output the gallery json for ingestion by Elementor
return $gallery_json;
}
?>