ap_upload_user_file( array $file = array(), boolean $temp = true, boolean $parent_post = '', false|array $mimes = false )

Description #

Upload and create an attachment. Set post_status as _ap_temp_media, later it will be removed using cron if no post parent is set.

This function will prevent users to upload if they have more then defined numbers of un-attached medias.

Parameters #

  • $file
    array (Optional) $_FILE variable. Default value: array()
  • $temp
    boolean (Optional) Is temporary image? If so it will be deleted if no post parent. Default value: true
  • $parent_post
    boolean (Optional) Attachment parent post ID. Default value: ''
  • $mimes
    false | array (Optional) Mime types. Default value: false

Changelog #

VersionDescription
4.1.5Added new argument $mimes so that default mimes can be overridden.
3.0.0Introduced.

Source #

File: includes/upload.php

function ap_upload_user_file( $file = array(), $temp = true, $parent_post = '', $mimes = false ) {
	require_once ABSPATH . 'wp-admin/includes/admin.php';

	// Check if file is greater then allowed size.
	if ( $file['size'] > ap_opt( 'max_upload_size' ) ) {
		// translators: %s is file size.
		return new WP_Error( 'file_size_error', sprintf( __( 'File cannot be uploaded, size is bigger than %s MB', 'anspress-question-answer' ), round( ap_opt( 'max_upload_size' ) / ( 1024 * 1024 ), 2 ) ) );
	}

	$file_return = wp_handle_upload(
		$file,
		array(
			'test_form' => false,
			'mimes'     => false === $mimes ? ap_allowed_mimes() : $mimes,
		)
	);

	if ( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
		return new WP_Error( 'upload_error', $file_return['error'], $file_return );
	}

	$attachment = array(
		'post_parent'    => $parent_post,
		'post_mime_type' => $file_return['type'],
		'post_content'   => '',
		'guid'           => $file_return['url'],
	);

	// Add special post status if is temporary attachment.
	if ( false !== $temp ) {
		$attachment['post_title'] = '_ap_temp_media';
	}

	require_once ABSPATH . 'wp-admin/includes/image.php';
	$attachment_id = wp_insert_attachment( $attachment, $file_return['file'] );

	if ( ! empty( $attachment_id ) ) {
		ap_update_user_temp_media_count();
	}

	return $attachment_id;
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Add your comment