Code Snippet to Create a Directory Within Uploads Folder

Here's a code snippet that allows your plugin to create a new folder in the /uploads directory on activation. Could be useful if your plugin needs to allow imports or uploads and you want them stored in a separate directory.
Table of Contents

Here’s a code snippet that allows your plugin to create a new folder in the /uploads directory on activation. Could be useful if your plugin needs to allow imports or uploads and you want them stored in a separate directory.

[php]
function myplugin_activate() {

$upload = wp_upload_dir();
$upload_dir = $upload[‘basedir’];
$upload_dir = $upload_dir . ‘/mypluginfiles’;
if (! is_dir($upload_dir)) {
mkdir( $upload_dir, 0700 );
}
}

register_activation_hook( __FILE__, ‘myplugin_activate’ );
[/php]
If you enjoyed this post, make sure to subscribe to WP Mayor’s RSS feed.

Jean Galea
Jean Galea
Jean Galea is an investor, entrepreneur, and blogger. He is the founder of WP Mayor, the plugins WP RSS Aggregator and Spotlight, as well as the Mastermind.fm podcast. His personal blog can be found at jeangalea.com.

Consider sharing this post so others can find it:

Join thousands of people receiving real-world, genuine evaluations of WordPress products and services just like this one every week.

Featured Deals

Bluehost is WP Mayor’s recommended WordPress shared hosting provider. Get up to $15 off every month on Bluehost’s shared hosting using the button below.

Get 4 months free on annual WP Engine hosting plans (or 20% off your first month on monthly plans) using our coupon code WPMAYOR20 at checkout.

Get an exclusive 15% discount on WooFunnels by clicking the link below. It’s the most powerful funnel builder for all types of WooCommerce stores.

3 Responses

  1. I prefer use the WP way than the PHP way:
    wp_mkdir_p( $upload_dir );
    or more techy:
    require_once( ABSPATH . ‘wp-admin/includes/class-wp-filesystem-base.php’ );
    require_once( ABSPATH . ‘wp-admin/includes/class-wp-filesystem-direct.php’ );
    $wp_fs_d = new WP_Filesystem_Direct( new StdClass() );
    if ( !$wp_fs_d->is_dir( $upload_dir ) && !$wp_fs_d->mkdir( $upload_dir, 0705 ) )
    wp_die( sprintf( __( ‘Impossible to create %s directory.’ ), $upload_dir ) );

    By the way, WP recommand a 705 CHMOD, not 700, and take care readers: do not use “$uploads” var name this is overwritten by WordPress.

Leave a Reply

Your email address will not be published.

Everything you need to create a website for less than $100. From your domain and hosting to picking a design, we cover it all.

WP Mayor’s Newsletter

Team photo

Hey, we’re Gaby, Prithu, and Mark. Every Friday we send you our best tutorials and latest reviews.

Enjoyed by thousands every week. Less than 0.2% of our followers unsubscribed last year.