I’ve been receiving a lot of requests for a tutorial showing How to upload image WordPress form so I finally gave in. Hopefully, this tutorial will save you the same confusion I suffered.
WordPress provides many functions which make any functionality easy and robust.Here same for image uploading functionality, we can easily manage using WordPress functions.
Read: Tags in WordPress
First of all let’s write basic HTML code which gives interface to choose image/file
1 2 3 4 5 6 7 | ` <form action="<?php echo get_permalink( $post->ID ); ?>" method="post" enctype="multipart/form-data" id="submit_form"> <label for="profile-image"></label> <input type="submit" class="submit" name="submit" value="<?php _e('Upload'); ?>" /> </form> |
You can write above code into any template file you have created into your theme.
Now the most important, PHP code which will upload image/file into uploads folder of WordPress which is in wp-contents.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | if (isset($_POST) && $_POST['submit'] != '') { if (isset($_FILES['profile-image']) && !empty($_FILES['profile-image']['name'])) { $data['profile-image-name'] = $_FILES['profile-image']['name']; //to assign name to variable $extension = strtolower(substr(strrchr($_FILES['profile-image']['name'], "."), 1)); // to get extension value if (!in_array($extension, $allowed)) { $errors - > add('submit_error', __('<strong>ERROR</strong>: Only jpg, gif, and png images are allowed.')); } else { /** WordPress Administration File API */ include_once(ABSPATH. 'wp-admin/includes/file.php'); /** WordPress Media Administration API */ include_once(ABSPATH. 'wp-admin/includes/media.php'); $overrides = array('test_form' => false); $file = wp_handle_upload($_FILES['profile-image'], $overrides, $time); if (!isset($file['error'])) { $data['profile-image'] = $file['url']; $data['profile-image-type'] = $file['type']; $data['profile-image-file'] = $file['file']; } else { $errors - > add('submit_error', __('<strong>ERROR</strong>: ').$file['error']); } } } } |
Must Read:ShortCode in WordPress
Here, you can add above code into your template file your functions.php file you require.
This tutorials was aimed at those just not clear about image/file uploading in WordPress so if you are confused about anything please leave a comment & I’ll try my best to help rescue you from the castle of confusion. As always, thanks for reading. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.
Comments (1)