Simple Tutorial Showing How To Use Composer in Your WordPress Plugin or Theme
I love Composer. It just makes including libraries or scripts in your app incredibly easy. So easy that it’s stupid not to use it (in many, if not most cases).
The number of libraries/scripts available on Packagist is astounding, all of which can be included in your plugin with Composer. Packagist is the main Composer repository. It basically aggregates all types of PHP packages that can be installed via Composer.
I’d never used Composer with a proprietary WordPress plugin before. The plugin is for a client so it’ll never be available to the public.
Here’s the steps I took to make this WordPress plugin compatible with Composer so that I can easily bring in third-party libraries.
1. First, install composer on your server.
I install Composer globally, like so:
curl -sS https://getcomposer.org/installer | php<br>sudo mv composer.phar /usr/local/bin/composer
2. Add Mailgun as a dependency.
cd /path/to/plugin/ composer require mailgun/mailgun-php:~1.7.2
3. Check your composer.json file.
4. Tell composer to install Mailgun.
tyler@yourmachine:~/path/to/plugin$ composer install
5. Autoload Our Mailgun Classes in Our Plugin.
The following should go in your
plugin-name.php file, before any other PHP code.
<?php require 'vendor/autoload.php'; use MailgunMailgun;