Hello, i try to duplicate ca CPT in frontend that heave several field ant a repeatable attachment custom field. I use this function to achieve that:
//* Duplicate CPT
add_action('cred_save_data_455', 'duplicate_post', 10, 2);
function duplicate_post($post_id, $form_data) {
// get data of original post
$post = get_post( $form_data['container_id'], ARRAY_A );
// update the new post with this data
$post['ID'] = $post_id;
$post['post_title'] = 'CopyOf ' . $post['post_title'];
wp_update_post( $post );
// get fields of original post
$fields = get_post_custom( $form_data['container_id'] );
// update the new post with these fields
foreach ($fields as $key => $values) {
foreach ($values as $value) {
$value = maybe_unserialize( $value );
add_post_meta($post_id, $key, $value, true);
}
}
}
Everything is working fine but the repeatable attachment type custom field is not duplicated entirely when i have attached several files - it is duplicating only the first attached file.
Please help my to achieve that all the attached file to be duplicated.
Thank you
Hi,
Thank you for contacting us and I'd be happy to assist.
The 4th parameter "$unique" in the 'add_post_meta' function, decides whether the custom field with the same key should be added or not:
https://developer.wordpress.org/reference/functions/add_post_meta/
Since the repeating fields use the custom fields with the same key, you should replace 'true' with 'false', in your custom function:
add_post_meta($post_id, $key, $value, false);
I hope this helps and let me know how it goes.
regards,
Waqar
My issue is resolved now. Thank you!