Changing upload dir in a plugin regardless of post type

I read this post and found it really interesting. I tried to modify it a little to make it work if you have a custom db table and not really a post type to rely on. So I tried to figure that out using get_current_screen() instead of get_post_type().

In this example I did a little plugin to register members of some kind (just for the idea of using this in any kind of plugin that doesn’t use post types) and have the profile photos upload to the plugin dir just like in the original code. Although this doesn’t seem to work, the files are still saved in the regular “wp-content/uploads/” dir. Any ideas?

Read More

The plugin itself uses a simple form to save data to db and I also hooked the wp-uploader to upload and send the image url with the rest of the data.

function custom_upload_directory( $args ) {

$screen = get_current_screen();

// If the parent_base is members, upload to plugin directory
if ( $screen->parent_base == ‘members’ ) {
    $args['path'] = plugin_dir_path(__FILE__) . “uploads”;
    $args['url'] = plugin_dir_url(__FILE__) . “uploads”;
    $args['basedir'] = plugin_dir_path(__FILE__) . “uploads”;
    $args['baseurl'] = plugin_dir_url(__FILE__) . “uploads”;
}
return $args;
}
add_filter( ‘upload_dir’, ‘custom_upload_directory’ );

Related posts

Leave a Reply

1 comment

  1. Typo: ‘ not is ‘

    You have a weired Editor. You’re simply using the wrong type of quotes:

    • “ should be "
    • ‘ should be '

    Here’s the changed function:

    function wpse43013_custom_upload_directory( $args ) 
    {
        // If the parent_base is "members", upload to plugin directory
        if ( 'members' === get_current_screen()->parent_base )
            return wp_parse_args( $args, array_fill_keys(
                 array( 'path', 'url', 'basedir', 'baseurl' )
                ,plugin_dir_path( __FILE__ ).'uploads'
            ) );
    
        return $args;
    }
    add_filter( 'upload_dir', 'wpse43013_custom_upload_directory' );
    

    Debug

    Normally that should throw an error. Be sure that you have set WP_DEBUG set to TRUE inside your wp-config.php file when testing code inside a development environment.

    define( 'WP_DEBUG', true );
    

    On production sites you could also enable the error log (don’t do this constantly and disable error display so errors are gracefully logged and not displayed to your users.

    define( 'WP_DEBUG', true );
    define( 'WP_DEBUG_LOG', true );
    define( 'WP_DEBUG_DISPLAY', false );
    @ini_set( 'display_errors', 0 );
    

    See the editing wp-config page for more info on defining configuration constants.