PHP Composer, WordPress

How To Use PHP Composer With WordPress Plugin / Theme

I’ve encountered this situation many times when I’m developing an advanced WordPress plugin or theme and I need to use a composer package. In advance developments, composer packages help a lot to build complex apps.

But I had few confusions and It was hard to decide how should I proceed. In this article, I’ll try to explain how to use PHP Composer with WordPress plugin or themes.

First thing first, Should You include composer vendor directory inside your plugin?

Yes, you must include composer vendor directory inside your project.

PHP scripts, apps are different than WordPress plugins and themes. You know when someone using your full script they are always developer or has enough knowledge to run composer install. But most of the WordPress users aren’t developers and they don’t want the hassle to run any commands while installing your plugin or themes. That’s why you must ship your plugins or themes with composer installed.

Ok, Enough explanation. Let’s start with a very basic WordPress plugin that does nothing. Here how it’s code looks like:

Create a plugin with the given code and activate from your wp dashboard.

Now navigate to the plugin folder in your terminal and run:

composer init

Follow the given instructions and complete the installation. Now include the composer autoload.php inside the plugin file.

Now we are going to register a shortcode that’s output current date time and to do that we are going to use a composer package. For the sake of simplicity, I’m using a very simple package to describe how you can use composer package but you can use any package you want.

To install the DateTime package run:

composer require nesbot/carbon

Now create a shortocdes.php file inside includes directory and paste the given codes below.

In the line number 2, we are using a namespace Carbon\Carbon to require the DateTime package as like you do in other PHP projects. In the line number 23, we are using 2 functions from the Carbon package to return the current DateTime.

Now open the main plugin file again and require the shortcodes.php file and create an instance of the Shortcodes class.

Final code:

Now go to edit any post or page and use the [current_datetime] shortcode. Then visit the post and you should see the current DateTime.

I hope this article describes how to use PHP composer with WordPress. Please leave a comment below if this article helped you.

Download the source file from this GitHub repository:

Tagged , , ,

About Robin

A learner who loves technology very much. Dreaming to become a programmer but also enjoying the life.
View all posts by Robin →

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.