Documentation

Filter wphd_file_upload

This filter allows you to add extra validation to file uploads before the file is saved on the server disk.

The example below will check if the file being uploaded has an allowed file extension; if not, the file upload will fail with an error.

// Assign a filter
add_filter( 'wphd_file_upload', 'my_wphd_file_upload' );


/**
 * Check if uploaded file extension is valid.
 *
 * This function is executed using 'wphd_file_upload' filter,
 * it stops file upload using die() if incorrect file type is sent
 *
 * @param array $file Element of $_FILES array
 * @return array
 */
function my_wphd_file_upload( $file ) {
    $allowed = array("pdf", "zip", "jpeg", "jpg", "gif", "png", "doc", "docx");
    $ext = pathinfo($file["name"], PATHINFO_EXTENSION);

    if( ! in_array( $ext, $allowed ) ) {
        $response = new stdClass();
        $response->result = 0;
        $response->msg = sprintf("Uploading file wit extension '%s' is not allowed.", $ext);
        die(json_encode($response));
    }

    return $file;
}

To use this code snippet you can paste it into your theme functions.php file.