title: How to limit file type to be upload in WordPress?
body: <p>I have a custom page template with a form, that any visitor of the website can upload a file. Now, I want to restrict the file type that will be upload (docx, doc and pdf only) and I limit the file size into 2MB only.</p>
  
  <p>How to do this? I already have a function that the user allowed to upload, but I don't know how to restrict the file type that allowed to be upload. Please help me.</p>
  
  <p><strong>Limiting the file is now working, but it's weird why the file is still save even the file is too large. How to fix this?</strong></p>
  
  <p>PHP in custom page template</p>
  
  <pre><code>if(isset($_POST['submit'])){
      $firstName = isset($_POST['firstName']) ? $_POST['firstName'] : '';
      $middleName = isset($_POST['middleName']) ? $_POST['middleName'] : '';
      $lastName = isset($_POST['lastName']) ? $_POST['lastName'] : '';
      $email = isset($_POST['email']) ? $_POST['email'] : '';
      $mobile = isset($_POST['mobile']) ? $_POST['mobile'] : '';
      $locations = isset($_POST['locations_list']) ? $_POST['locations_list'] : '';
      $position = isset($_POST['position']) ? $_POST['position'] : '';
      $message = isset($_POST['message']) ? $_POST['message'] : '';
          if( ! empty($_FILES)){
              $file=$_FILES['file'];
              $attachment_id = upload_user_file($file);
          }
  
  if ($_FILES["file"]["size"] &gt; 1048576){
                  echo "Sorry, your file is too large.";
                  $uploadOk = 0;
          }
  }
  </code></pre>
  
  <p>PHP in functions.php</p>
  
  <pre><code>function upload_user_file($file = array()){
      require_once(ABSPATH . 'wp-admin/includes/admin.php');
        $file_return = wp_handle_upload($file, array('test_form' =&gt; false));
        if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
            return false;
        } else {
            $filename = $file_return['file'];
            $attachment = array(
                'post_mime_type' =&gt; $file_return['type'],
                'post_title' =&gt; preg_replace('/\.[^.]+$/', '', basename($filename)),
                'post_content' =&gt; '',
                'post_status' =&gt; 'inherit',
                'guid' =&gt; $file_return['url']
            );
  
            $attachment_id = wp_insert_attachment($attachment, $file_return['url']);
  
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            $attachment_data = wp_generate_attachment_metadata($attachment_id, $filename);
            wp_update_attachment_metadata($attachment_id, $attachment_data);
  
            if(0 &lt; intval($attachment_id)){
              return $attachment_id;
            }
        }
        return false;
  }
  </code></pre>