Created
July 18, 2025 08:36
-
-
Save moxet/0d5b779b993eabec10e14a91c9a33085 to your computer and use it in GitHub Desktop.
Save Image from REST API to Wordpress
This file contains hidden or 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
| add_action('jet-form-builder/custom-action/saveimage', function( $request, $action_handler ) { | |
| $image_url = $request['image_file']; | |
| $post_id = $request['inserted_post_id']; | |
| // Get image data from URL | |
| $image_data = file_get_contents($image_url); | |
| // Set the path to the WordPress uploads directory | |
| $upload_dir = wp_upload_dir(); | |
| // Set the file name for the image | |
| $file_name = basename($image_url); | |
| // Set the full path for the image file | |
| $file_path = $upload_dir['path'] . '/' . $file_name; | |
| // Save the image to the uploads directory | |
| file_put_contents($file_path, $image_data); | |
| // Determine the image file type | |
| $file_type = wp_check_filetype($file_name, null); | |
| // Prepare attachment data | |
| $attachment_data = array( | |
| 'post_mime_type' => $file_type['type'], | |
| 'post_title' => sanitize_file_name($file_name), | |
| 'post_content' => '', | |
| 'post_status' => 'inherit', | |
| ); | |
| // Insert attachment to WordPress | |
| $attachment_id = wp_insert_attachment($attachment_data, $file_path, $post_id); | |
| // Set as featured image (thumbnail) | |
| set_post_thumbnail($post_id, $attachment_id); | |
| }, 10, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment