Share this: Twitter

Reddit

Email

LinkedIn

Facebook



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.

We’ll be using mailgun-php throughout this example, as the plugin that inspired this post uses Mailgun to send all sorts of emails.

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.

We’re including Mailgun and guzzle from Packagist. Your composer.json file should look similar to the example below.



View the code on Gist.

4. Tell composer to install Mailgun.

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;

You can now use Mailgun in your WordPress plugin or theme, some basic examples of using Mailgun can be found on GitHub and in their official documentation.

2+

Well, now what? Work with Me I'm available for hire and always taking new clients, big and small. Got a project or an idea you'd like to discuss? Startup plan but no developer to make it happen? Just get in touch, I'd love to see if I can help you out! Leave some Feedback Got a question or some updated information releavant to this post? Please, leave a comment! The comments are a great way to get help, I read them all and reply to nearly every comment. Let's talk. 😀 Longren.io is proudly hosted by DigitalOcean

Share this: Twitter

Reddit

Email

LinkedIn

Facebook



Like this: Like Loading...