WordPress provides ready functions for handling file uploads and image manipulation.
It is always best practice to use built-in WordPress functions for checking the file, moving it and setting file permissions. We will use these functions in the following example.
Let's add a function to handle images uploaded by the user. The function uses the built-in
wp_handle_upload()
function:function handle_image_upload($upload) { // check if image if (file_is_displayable_image( $upload['tmp_name'] )) { // handle the uploaded file $overrides = array('test_form' => false); $file=wp_handle_upload($upload, $overrides); } return $file; }
Now, we need to include the image to our post. Let's expand the
display_form()
function to include handling of uploaded images and inserting a new post with attachment:
// Display the Post form function display_form() { global $wpdb; $page=$_GET['page']; $published=isset($_POST['publish']); $title...