Created
February 19, 2018 14:34
-
-
Save New0/9346ab0f14b114e59fbbd7b2345ccf8d to your computer and use it in GitHub Desktop.
Get data of a Caldera Forms multiple files field and save the files in an ACF gallery custom field
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
<?php | |
/* | |
* This function is copied from https://wpscholar.com/blog/get-attachment-id-from-wp-image-url/ | |
* | |
* Function to get the attachment ID of a media file based on its URL in WordPress | |
* | |
*/ | |
function get_attachment_id( $url ) { | |
$attachment_id = 0; | |
$dir = wp_upload_dir(); | |
if ( false !== strpos( $url, $dir['baseurl'] . '/' ) ) { // Is URL in uploads directory? | |
$file = basename( $url ); | |
$query_args = array( | |
'post_type' => 'attachment', | |
'post_status' => 'inherit', | |
'fields' => 'ids', | |
'meta_query' => array( | |
array( | |
'value' => $file, | |
'compare' => 'LIKE', | |
'key' => '_wp_attachment_metadata', | |
), | |
) | |
); | |
$query = new WP_Query( $query_args ); | |
if ( $query->have_posts() ) { | |
foreach ( $query->posts as $post_id ) { | |
$meta = wp_get_attachment_metadata( $post_id ); | |
$original_file = basename( $meta['file'] ); | |
$cropped_image_files = wp_list_pluck( $meta['sizes'], 'file' ); | |
if ( $original_file === $file || in_array( $file, $cropped_image_files ) ) { | |
$attachment_id = $post_id; | |
break; | |
} | |
} | |
} | |
} | |
return $attachment_id; | |
} | |
/* | |
* Transform data from file field and update gallery custom field | |
* | |
*/ | |
add_action( 'caldera_forms_submit_complete', function( $form, $referrer, $process_id, $entryid ) { | |
//change your form ID here | |
if( 'CF5a5e8452c6f82' != $form[ 'ID' ] ) { | |
return; | |
} | |
//change your field ID here | |
$imgs = Caldera_Forms::get_field_data( 'fld_6467937', $form ); | |
$attachments_array = array(); | |
if( !empty($imgs) ) { | |
foreach( $imgs as $img_url ){ | |
$img_id = get_attachment_id( $img_url ); | |
$attachments_array[] = $img_id; | |
} | |
} | |
//Change the field ID of the hidden field using {post_type:ID} magic tag as value | |
$pid = Caldera_Forms::get_field_data( 'fld_6098178', $form ); | |
$post_id = Caldera_Forms::do_magic_tags( $pid, $entryid ); | |
//Update the ACF custom field ID | |
if( !empty( $attachments_array ) && !empty( $post_id ) { | |
update_field( 'field_0000000000', $attachments_array , $post_id ); | |
} | |
}, 10, 4 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment