Abdul Muqsit

Abdul Muqsit

Founder
SoftEmblems.com
admin@softemblems.com

JetFormBuilder Update Field | Selective Post from WordPress REST API

In this tutorial, you ll learn how to use selective data from REST API endpoints and insert in your WordPress website using JetFormBuilder.

You might came across a situation where you need dozens of fields to be filled using the form such as inserting vehicle records from 3rd party REST API in your website. In such cases this logic will help you insert those records with few clicks.

Download Jet Form Builder Update Fields Add-on

If you want to take the game a step further and insert the URL as an attachment in WordPress post just like the example I shared, feel free to use the following code in form hook.

<?php

add_action( 'jet-form-builder/custom-action/saveimage', function( $request, $action_handler ) {
	
$image_url = $request["image_file"];


$post_id = $request['inserted_post_id'];

$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 path for the image file
$file_path = $upload_dir['path'] . '/' . $file_name;

// Save the image file to the uploads directory
file_put_contents($file_path, $image_data);

// Set the image file type
$file_type = wp_check_filetype($file_name, null);

// Prepare an array of attachment data
$attachment_data = array(
    'post_mime_type' => $file_type['type'],
    'post_title' => sanitize_file_name($file_name),
    'post_content' => '',
    'post_status' => 'inherit'
);

// Insert the image as an attachment
$attachment_id = wp_insert_attachment($attachment_data, $file_path, $post_id);

// Set the post thumbnail (featured image) using the attachment ID
set_post_thumbnail($post_id, $attachment_id);

	
}, 10, 2 );