Use PHP Composer in a WordPress Theme or Plugin to Load Third-Party Libraries

Composer is PHP’s package manager, similar to Pip for Python or npm for Node.js. Once we have Composer, using a PHP library in a PHP project becomes much easier. WordPress is built with PHP, so it is completely natural to use Composer to manage the PHP libraries used by a WordPress theme or plugin.

Composer-compatible PHP libraries can be found on Packagist.org, which is Composer’s official repository. Before using a library, search for it on Packagist. If it is available there, we can install and manage it with Composer.

Below I will explain how to use Composer in a WordPress theme or plugin to manage third-party PHP libraries. In the example below, we will use the mailgun-php library.

1. First, install Composer

Use the official install command. If you are on Windows, you can install it with the official Composer-Setup.exe package.

wpzhiku@ubutnu:~$ curl -sS https://getcomposer.org/installer | php
wpzhiku@ubutnu:~$ sudo mv composer.phar /usr/local/bin/composer

2. Then add Mailgun as a dependency

Use Composer’s require command to add the library we need. This command downloads the library files and generates the autoload file for us.

wpzhiku@ubutnu:~$ cd /path/to/plugin/
wpzhiku@ubutnu:~/path/to/plugin$ composer require mailgun/mailgun-php:~1.7.2

3. Check the composer.json file to confirm it was added successfully

After step 2, the composer.json configuration file should look something like this.

{
  "name": "plugin-name/plugin",
  "description": "Your plugin description",
  "keywords": ["wordpress", "plugin", "private"],
  "homepage": "https://longrendev.io/",
  "license": "proprietary",
  "authors": [
    {
      "name": "wpzhiku",
      "email": "wpzhiku@qq.com",
      "homepage": "https://wphrefs.com/"
    }
  ],
  "type": "wordpress-plugin",
  "require": {
    "php": ">=5.3.2",
    "composer/installers": "v1.0.6",
    "mailgun/mailgun-php": "~1.7.2",
    "guzzlehttp/guzzle": "~5.2"
  }
}

4. Install Mailgun through Composer

If we added the library manually to composer.json, we need to run the following command to install the dependency.

wpzhiku@ubutnu:~/path/to/plugin$ composer install

5. Autoload the Mailgun class in the plugin

PHP has supported namespaces since version 5.3. If your PHP version is 5.3 or higher, you can load the Mailgun class like this by placing the following code at the top of the plugin file.

require 'vendor/autoload.php';
use MailgunMailgun;

Of course, we can also add the same code to a WordPress theme’s functions.php file to load the installed library into the theme.

Once that step is complete, we can start using Mailgun features in the plugin or theme. It is a very convenient workflow.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *