Function and usage of media_handle_upload() in wordpress


Answers ( 1 )


    The media_handle_upload() function in WordPress is an essential tool for developers working with file uploads. It enables the handling and processing of files submitted through a POST request, creating an attachment post for each uploaded file. This function is particularly useful when you want to programmatically attach media to posts or handle media uploads in custom forms.

    Function Signature

        string $file_id,
        int $post_id,
        array $post_data = array(),
        array $overrides = array('test_form' => false)
    ): int|WP_Error


    1. $file_id (string, required): This parameter represents the index within the $_FILES array where the file data is stored. The $_FILES array is a global PHP variable that stores all information about files uploaded via POST.

    2. $post_id (int, required): This is the ID of the post to which the media item will be attached. If this parameter is set to 0, it creates a media item that isn't attached to any post.

    3. $post_data (array, optional): This array allows overwriting some of the attachment properties. It's an associative array where keys are the names of the properties to overwrite, and the values are the new values for those properties. The default is an empty array.

    4. $overrides (array, optional): This parameter is used to override certain behaviors of the wp_handle_upload() function. It includes settings like error handling, file naming, and file type checks. The default value is an array with 'test_form' => false, which disables the check for a valid form submission.

      • upload_error_handler (callable): Function called when there is an upload error.
      • unique_filename_callback (callable): Function called to generate a unique file name.
      • upload_error_strings (string[]): Descriptions for upload error codes.
      • test_form (bool): Whether to validate the form submission.
      • test_size (bool): Whether to check the file size.
      • test_type (bool): Whether to validate the file type.
      • mimes (string[]): Array of allowed mime types.

    Return Value

    • int|WP_Error: The function returns the ID of the attachment post created for the uploaded file. If the upload or attachment creation fails, it returns a WP_Error object.

    Example Usage

    if ( isset( $_FILES['your_form_file_input_name'] ) ) {
        $attachment_id = media_handle_upload( 'your_form_file_input_name', $parent_post_id );
        if ( is_wp_error( $attachment_id ) ) {
            // Handle the error.
        } else {
            // The file was uploaded successfully!

    In this example, your_form_file_input_name is the name attribute of the file input in your form. $parent_post_id is the ID of the post to which you want to attach the uploaded file. The function handles the file upload and attachment creation, returning either the attachment ID or an error object.

Leave an answer