Last active
July 22, 2021 11:43
-
-
Save ideag/5582256 to your computer and use it in GitHub Desktop.
Wordpress frontend file uploading
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// simple frontend file upload | |
// written by Arūnas Liuiza | tinyStudio | wp.tribuna.lt | |
// Usage: use [tiny_upload] shortcode or get_tiny_upload()/the_tiny_upload() template tags | |
// Localization: replace 'theme' with your text domain string. | |
// ======= UPLOAD FORM =====> | |
// return form #1 | |
// usage: $result = get_tiny_upload(); | |
function get_tiny_upload($redirect=false) { | |
$return = "<form action=\"\" method=\"post\" class=\"tiny_form tiny_upload\" enctype=\"multipart/form-data\" >\r\n"; | |
$return .= " <p> | |
<label for=\"tiny_upload\">".__('File','theme')."</label> | |
<input type=\"file\" id=\"tiny_upload\" name=\"tiny_upload\"/> | |
</p>\r\n"; | |
// where to redirect on success | |
if ($redirect) | |
$return .= " <input type=\"hidden\" name=\"redirect\" value=\"{$redirect}\">\r\n"; | |
$return .= " <input type=\"hidden\" name=\"tiny_action\" value=\"upload\">\r\n"; | |
$return .= " <button type=\"submit\">".__('Upload','theme')."</button>\r\n"; | |
$return .= "</form>\r\n"; | |
return $return; | |
} | |
// print form #1 | |
/* usage: <?php the_tiny_upload(); ?> */ | |
function the_tiny_upload($redirect=false) { | |
echo get_tiny_upload($redirect); | |
} | |
// shortcode for form #1 | |
// usage: [tiny_upload] in post/page content | |
add_shortcode('tiny_upload','tiny_upload_shortcode'); | |
function tiny_upload_shortcode ($atts,$content=false) { | |
$atts = shortcode_atts(array( | |
'redirect' => false | |
), $atts); | |
return get_tiny_upload($atts['redirect']); | |
} | |
// <============== UPLOAD FORM | |
// ============ FORM SUBMISSION HANDLER | |
add_action('init','tiny_handle'); | |
function tiny_handle() { | |
if (isset($_POST['tiny_action'])) { | |
switch ($_POST['tiny_action']) { | |
case 'upload': | |
require_once(ABSPATH . 'wp-admin/includes/admin.php'); | |
// step one upload file to server | |
$file_return = wp_handle_upload($_FILES['tiny_upload'], array('test_form' => false)); | |
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])) { | |
// echo 'not working again :('; | |
} | |
else { | |
$filename = $file_return['file']; | |
// do something with the uploaded file | |
$success = true; | |
} | |
break; | |
} | |
// if redirect is set and action was successful | |
if (isset($_POST['redirect']) && $_POST['redirect'] && $success) { | |
wp_redirect($_POST['redirect']); | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment