acf_upload_file()ACF 5.0.9

acf_upload_file

This function will uploade a $_FILE

Hooks from the function

Returns

$id. (int) new attachment ID

Usage

acf_upload_file( $uploaded_file );
$uploaded_file(required)
.

Changelog

Since 5.0.9 Introduced.

acf_upload_file() code ACF 6.8.8

function acf_upload_file( $uploaded_file ) {

	// required
	// require_once( ABSPATH . "/wp-load.php" ); // WP should already be loaded
	require_once ABSPATH . '/wp-admin/includes/media.php'; // video functions
	require_once ABSPATH . '/wp-admin/includes/file.php';
	require_once ABSPATH . '/wp-admin/includes/image.php';

	// required for wp_handle_upload() to upload the file
	$upload_overrides = array( 'test_form' => false );

	// Restrict uploads to image MIME types for image and gallery fields.
	// phpcs:disable WordPress.Security.NonceVerification.Missing -- Field key is used for validation context only.
	if ( ! empty( $_POST['_acfuploader'] ) ) {
		$field = acf_get_field( sanitize_text_field( wp_unslash( $_POST['_acfuploader'] ) ) );
		if ( acf_is_image_field( $field ) ) {
			$upload_overrides['mimes'] = acf_get_image_mime_types( $field );
		}
	}
	// phpcs:enable WordPress.Security.NonceVerification.Missing

	// upload
	$file = wp_handle_upload( $uploaded_file, $upload_overrides );

	// bail early if upload failed
	if ( isset( $file['error'] ) ) {
		return $file['error'];
	}

	// vars
	$url      = $file['url'];
	$type     = $file['type'];
	$file     = $file['file'];
	$filename = basename( $file );

	// Construct the object array
	$object = array(
		'post_title'     => $filename,
		'post_mime_type' => $type,
		'guid'           => $url,
	);

	// Save the data
	$id = wp_insert_attachment( $object, $file );

	// Add the meta-data
	wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );

	/** This action is documented in wp-admin/custom-header.php */
	do_action( 'wp_create_file_in_uploads', $file, $id ); // For replication

	// return new ID
	return $id;
}