I have added some custom fields to Restrict content pro registration form. All are working fine except for the file upload, its not working. The $_FILES['rcp_gallery']
shows as undefined in error log. I have removed the other working fields to simply the code. They were simple text inputs.
class Setup {
public function __construct() {
add_action( 'rcp_after_password_registration_field', [ $this, 'rcp_add_custom_fields' ] );
add_action( 'rcp_form_processing', [ $this, 'rcp_save_custom_fields' ], 10, 2 );
add_action( 'rcp_form_processing', [ $this, 'rcp_validate_custom_fields' ], 10, 2 );
}
/**
* # RCP Pro custom add field
*/
public function rcp_add_custom_fields() {
?>
<!-- Gallery -->
<p id="rcp_gallery_wrap">
<label for="rcp_gallery"><?php echo sprintf( esc_html__( 'Gallery of work %s(Required)%s', 'fmaa' ), '<em class="text-danger ms-2">', '</em>' ); ?></label>
<input type="file" id="rcp_gallery" class="required" name="rcp_gallery[]" multiple>
</p>
<?php
}
/**
* # RCP Pro save custom fields
*/
public function rcp_save_custom_fields( $posted_data, $user_id ) {
// Gallery
if ( isset( $_FILES['rcp_gallery'] ) && ! empty( $_FILES['rcp_gallery']['name'][0] ) ) {
$gallery_ids = [];
// Include necessary WordPress files for handling file uploads
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
foreach ( $_FILES['rcp_gallery']['name'] as $key => $value ) {
if ( $_FILES['rcp_gallery']['name'][$key] ) {
$file = [
'name' => $_FILES['rcp_gallery']['name'][$key],
'type' => $_FILES['rcp_gallery']['type'][$key],
'tmp_name' => $_FILES['rcp_gallery']['tmp_name'][$key],
'error' => $_FILES['rcp_gallery']['error'][$key],
'size' => $_FILES['rcp_gallery']['size'][$key],
];
// Upload file to the WordPress media library
$attachment_id = media_handle_upload( 'rcp_gallery', 0, $file );
if ( is_wp_error( $attachment_id ) ) {
error_log( 'Media upload error: ' . $attachment_id->get_error_message() );
continue;
} else {
$gallery_ids[] = $attachment_id; // Add the attachment ID to the gallery IDs array
}
}
}
$gallery_ids_string = implode( ',', $gallery_ids );
update_user_meta( $user_id, 'fmaa_gallery', $gallery_ids_string );
}
}
/**
* # RCP Pro custom fields validation
*/
public function rcp_validate_custom_fields( $posted_data, $user_id ) {
// Validate Gallery
if ( empty( $_FILES['rcp_gallery']['name'][0] ) ) {
rcp_errors()->add( 'gallery_missing', esc_html__( 'Please upload your gallery of work.', 'fmaa' ), 'register' );
}
}
}
new Setup();