Hello,
I have a form that uploads images. i want have them added to postmeta ‘images’ automatically
ive tried a few option and Eric on FB mentioned ‘bricks/form/response’ but i cant find any docs on it
From what ive seen with a custom message in another topic i have the following code. but i feel like this is too much and im missing something easier…
Any ideas would be appreciated… If theres a better way to publicly upload photos to a post im all ears
function my_form_custom_action($form) {
$fields = $form->get_fields();
$formId = $fields['formId'];
// Ensure this matches your actual form ID
if ($formId !== 'azovhw') {
return;
}
// Retrieve the post ID from the URL
$post_id = isset($_GET['post']) ? sanitize_text_field($_GET['post']) : '';
error_log('Post ID from $_GET: ' . print_r($post_id, true));
// Ensure the post ID is valid
if (!$post_id || !is_numeric($post_id)) {
error_log('Invalid or missing post ID.');
$form->set_result([
'action' => 'my_custom_action',
'type' => 'error',
'message' => 'Invalid post ID.',
]);
return;
}
// Retrieve the form response
$response = $form->get_response();
if (isset($response['files']) && is_array($response['files'])) {
$image_ids = []; // Array to store image IDs
foreach ($response['files'] as $file) {
if (isset($file['id']) && is_numeric($file['id'])) {
$image_id = intval($file['id']);
$attachment = get_post($image_id);
if ($attachment && 'attachment' === $attachment->post_type && wp_attachment_is_image($image_id)) {
$image_ids[] = $image_id;
} else {
error_log('File ID ' . $image_id . ' is not a valid image attachment.');
}
}
}
// Save image IDs to post meta
if (!empty($image_ids)) {
update_post_meta($post_id, 'images', $image_ids);
}
} else {
error_log('No files included in the form response.');
}
// Set success result
$form->set_result([
'action' => 'my_custom_action',
'type' => 'success',
'message' => 'Images saved successfully.',
]);
}
add_action('bricks/form/custom_action', 'my_form_custom_action', 10, 1);
function my_custom_response($response, $form) {
$results = $form->get_results();
// Loop through success results and check for custom action
if (isset($results['success'])) {
foreach ($results['success'] as $result) {
if ($result['action'] === 'my_custom_action') {
$response['message'] = $result['message'];
break;
}
}
}
return $response;
}
add_filter('bricks/form/response', 'my_custom_response', 10, 2);