Building a better media uploader for WordPress

You can use WordPress’s built in upload handler, wp_handle_upload(). You can use the upload_dir filter to set the custom directory.

Here are some code snippits from one of my plugins that you can use/modify:

public function saveCustomFields()
{
    global $post;

    if($post->post_type == self::POST_TYPE && current_user_can( 'edit_post', $post->ID ) )
    {
        if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
            return;

        $fileReference="installPDF"; // This has to be in a variable because it gets passed by reference to wp_handle_upload()

        // save normal custom fields w/ update_post_meta() here

        if( empty($_FILES[$fileReference] ) )
        {
            // your custom logic if needed
        }
        else
        {
            $overrides = array(
                'test_form' => false,
                'unique_filename_callback' => self::PREFIX . 'setFilename'      // this lets you rename the file
            );

            $result = wp_handle_upload( $_FILES[$fileReference], $overrides );

            if( is_array($result) && array_key_exists('error', $result) && !empty( $result['error'] ) )
            {
                // failure logic
            }
            else
            {
                // success logic
            }
        }
    }
}
add_action( 'post_updated', array( $this, 'saveCustomFields') );

public function addFormEnctype()
{
    // this is needed to enable file uplodas on your form

    echo ' enctype="multipart/form-data"';
}   
add_action( 'post_edit_form_tag',   array( $this, 'addFormEnctype') );

public function setUploadDirectory($uploads)
{
    global $post;

    if( $post->post_type == self::POST_TYPE )
    {
        $uploads['path']    = $this->uploadDir . $this->uploadYear ."https://wordpress.stackexchange.com/";
        $uploads['url']     = $this->uploadURL . $this->uploadYear ."https://wordpress.stackexchange.com/";
        $uploads['subdir']  = "https://wordpress.stackexchange.com/". $this->uploadYear;
        $uploads['basedir'] = $this->uploadDir;
        $uploads['baseurl'] = $this->uploadURL;
    }   

    return $uploads;
}
add_filter( 'upload_dir',           array( $this, 'setUploadDirectory') );

Leave a Comment