Create a clean zip file of your WordPress plugin folder

Want to zip up your custom plugin for distribution, but don't want that huge node_modules directory or package.json to get shipped along with it? There's a script for that.

Time to ship that plugin. Let’s get it zipped up for easy install using the WordPress control panel. I notice the zip progress bar running for much longer than it should; Oh crap, I’m zipping up the entire ./node_modules/ directory. Doh!

Rookie mistake. We only want to zip up files necessary to run the plugin on the server. No development-specific files need to be shipped and will just balloon the size of your WordPress plugin zip file.

No WordPress developer I know likes to manually extract out files and folders of a plugin in order to get them zipped. I created a handy plugin bundling script to make this easier; it can be run on the command line or terminal (assuming you have PHP CLI operational).

The good stuff

Drop a php file into the root of your plugin. I call mine bundle.php. Paste this code into the file:

<?php

$PLUGIN_NAME = 'custom-plugin';
$DIRS        = ['dist/', 'inc/'];

// Make sure our zipping class exists
if ( ! class_exists( 'ZipArchive' ) ) {
	die( 'Cannot find class ZipArchive' );
}

$zip = new ZipArchive();

// Set the system path for our zip file
$filepath = __DIR__ . '/' . $PLUGIN_NAME . '.zip';

// Remove any existing file with that filename
if ( file_exists( $filepath ) )
	unlink( $filepath );

// Create and open the zip file
if ( ! $zip->open( $filepath, ZipArchive::CREATE ) ){
	die( 'Failed to create zip at ' . $filepath );
}

// Add our main plugin file
$zip->addFile( __DIR__ . '/' . $PLUGIN_NAME . '.php', $PLUGIN_NAME . '.php' );

// Add our readme file
$zip->addFile( __DIR__ . '/readme.txt', 'readme.txt' );

// Add any other files by directory
foreach ( $DIRS as $dir ){
	
	foreach ( glob( __DIR__ . '/'. $dir .'/*.*') as $file ) {
		$zip->addFile( $file, $dir . basename( $file ) );
	}
}

$zip->close();

Out-of-the-box, this script will extract a dist/ folder, an inc/ folder, the readme.txt file and the main plugin PHP file. Feel free to configure it for your needs.

It’s based on the directory structure here, so change the $PLUGIN_NAME and $DIRS array to match your own situation.

Custom plugin folder

After running php bundle.php on your terminal from the plugin root, a clean and light-weight copy of your plugin will be zipped and placed in the root of your plugin folder. The contents based on the previous screen will look like this:

Zipped plugin structure

Okay, hopefully you were able to get that to work and can now start saving time when deploying new versions of your custom plugin as a zip file.