Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created January 16, 2018 15:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tommcfarlin/51b158a2cbc4052bef12cc059837a6ee to your computer and use it in GitHub Desktop.
Save tommcfarlin/51b158a2cbc4052bef12cc059837a6ee to your computer and use it in GitHub Desktop.
[WordPress] Uploading Files in WordPress Revisited, Part 2 - The Server Side
<form method="post"
enctype="multipart/form-data"
action="<?php echo esc_html(admin_url('admin-post.php')); ?>"">
<!-- Snip For Brevity --->
<?php
wp_nonce_field(
'acme-item-upload',
'acme-item-importer'
);
?>
</form>
<?php
/**
* Assuming the user has permission, verifies the security nonce and uploads the PDF file to the `uploads`
* directory and the Media Library.
*/
public function save()
{
if (!$this->userCanSave('acme-item-importer', 'acme-item-upload')) {
return;
}
// More to come...
}
<?php
/**
* Determines if the current user has permission to upload a file based on their current role and the values
* of the security nonce.
*
* @param string $nonce The WordPress-generated nonce.
* @param string $action The developer-generated action name.
* @return bool True if the user has permission to save; otherwise, false.
*/
private function userCanSave($nonce, $action)
{
$isNonceSet = isset($_POST[$nonce]);
$isValidNonce = false;
if ($isNonceSet) {
$isValidNonce = wp_verify_nonce($_POST[$nonce], $action);
}
return ($isNonceSet && $isValidNonce);
}
<?php
$file = $_FILES['acme-item-file']['tmp_name'];
$filename = basename($_FILES['acme-item-file']['name']);
$uploadFile = wp_upload_bits($filename, null, file_get_contents($file));
<?php
$file_type = explode('.', $filename);
$file_type = strtolower($file_type[count($file_type) - 1]);
if ('pdf' !== $file_type) {
// Give your feedback of choice here.
}
<?php
if ($uploadFile['error']) {
// Your preferred method of feedback here.
}
<?php
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
$attachment = array(
'post_mime_type' => 'pdf',
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_status' => 'inherit'
);
<?php
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
$attachment = array(
'post_mime_type' => 'pdf',
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment($attachment, $uploadFile['file']);
<?php
wp_safe_redirect(
$_REQUEST['_wp_http_referer'],
301
);
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment