Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active January 15, 2018 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/79c7f788488e6dc84079fcf3795fa417 to your computer and use it in GitHub Desktop.
Save tommcfarlin/79c7f788488e6dc84079fcf3795fa417 to your computer and use it in GitHub Desktop.
[WordPress] Uploading Files in WordPress, Revisited: Part 1 - The Client Side
<?php
/**
* Displays whenever a person tries to upload a file that isn't a PDF. This is toggled via JavaScript.
*/
?>
<div id="invalid-file-message" class="error notice is-dismissible" style="display:none;">
<p>You have attempted to upload an invalid file type.</p>
<button type="button" class="notice-dismiss">
<span class="screen-reader-text">Dismiss this notice.</span>
</button>
</div><!-- #invalid-file-message -->
var _monitorFileInput = function() {
var filename, filename_parts, file_type,
$invalidFileMessage = $('#invalid-file-message');
// When the user attempts to upload the file, check the file extension. If it's not PDF, then ignore it;
// otherwise, allow the user to attempt to upload the file and we'll check it on the server-side.
$('#acme-new-item-report-file').change(function() {
// Read the file type.
filename = $(this).val();
filename_parts = filename.split('.');
file_type = filename_parts[filename_parts.length - 1].toLowerCase();
// Determine if it looks valid or not.
if('pdf' !== file_type || '' === file_type) {
$invalidFileMessage.show();
$('#acme-upload-pdf').attr('disabled', 'disabled');
return;
}
// Remove the 'Disabled' attribute and hide the error message, if visible.
$('input[type="submit"]').removeAttr('disabled');
$invalidFileMessage.hide();
});
};
<?php
public function enqueue()
{
if (!is_admin() 'acme-upload-pdf' !== get_current_screen()->id) {
return;
}
wp_enqueue_script(
'acme-upload-pdf-admin',
$this->pluginUrl . 'assets/scripts/admin.js',
['jquery'],
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment