Gravity form Create post on form submission with ACF gallery field data
Wed Nov 27 2024 17:38:58 GMT+0000 (Coordinated Universal Time)
Saved by
@shusanto
if (!function_exists('media_sideload_image')) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
}
add_action('gform_after_submission_2', 'create_gallery_post_after_submission', 10, 2);
function create_gallery_post_after_submission($entry, $form) {
// Include necessary functions for media handling
if (!function_exists('media_sideload_image')) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
}
// Define your custom post type
$post_type = 'gallery';
// Prepare post data
$post_data = array(
'post_title' => rgar($entry, '5'), // Assuming field ID 5 is the title
'post_content' => '', // Assuming field ID 2 is the content
'post_status' => 'publish',
'post_type' => $post_type,
);
// Insert the post into the database
$post_id = wp_insert_post($post_data);
// Get the image URLs from entry
$image_urls = json_decode(rgar($entry, '1')); // Assuming field ID 1 contains the JSON array string
$image_ids = array(); // Array to hold the IDs of uploaded images
// Loop through each image URL
if (is_array($image_urls)) {
foreach ($image_urls as $image_url) {
// Upload the image to the Media Library
$image_id = media_sideload_image($image_url, $post_id, null, 'id');
if (!is_wp_error($image_id)) {
$image_ids[] = $image_id; // Collect the image ID
}
}
}
// Optionally, you can set post meta for the uploaded images
if (!empty($image_ids)) {
update_post_meta($post_id, 'gallery_images', $image_ids); // Store the array of image IDs
}
}
content_copyCOPY
Comments