I recently started another stint of learning. I will be starting some Gutenberg block development soon, so I wanted to research it and other things that can help on my journey. A little WP-CLI here, a little NPM there, you get the picture. Since composer has come up a couple times, I decided to take a deeper dive into it.
Revisiting Composer in Existing Project
I am working on a project that needed custom fields. Normally I would just create my own meta fields, but the requirements for this one are a bit complex. Advanced Custom Fields Pro would be an option, but the recurring cost of premium plugins isn’t ideal. Instead I decided to use Carbon Fields, a free open source alternative. It has a few installation options, one of which is as a stand-alone plugin using composer.
Failed Installation Attempt
When I tried it the composer option first time it failed, and threw a fatal error in WordPress. After a short while I gave up, and installed the pre-built plugin manually. I have had to update it manually too. Given my new experience with composer, I decided to give it another try. I did my best to follow the documentation on their website, and the installation failed again.
The documentation said to run composer require htmlburger/carbon-fields-plugin
from the root of the WordPress install. When I did that, a Carbon Fields folder and various contents were placed in the plugins folder. I thought that was it, it should be built and working, but it wasn’t.
Where I Went Wrong
After comparing the pre-built plugin to the plugin that was created with the composer command, I found that it wasn’t fully built. I also noticed that it has a composer.json file of its own. I assumed that the dependencies in that file would be installed when running the install command at the WordPress root, but I was wrong. This is where the confusion lies. I needed to also run composer install
or composer update
from the plugin’s directory. This was not in the Carbon Fields documentation. I can’t really blame them, it isn’t their job to teach me how to use composer. Now that I realized that it is not poor documentation, nor a bug in the code, but rather a PEBKAC error, I carry on.
Scaling
Assuming I want to start using composer on more plugins and themes, I wanted to find a way to quickly update everything without navigating to each directory. The following script will run updates on all composer projects in the WordPress root, as well as the plugin and theme directories.
#!/bin/bash
composer update
for dir in {*,wp-content/plugins/*,wp-content/themes/*}
do
if [ -d $dir ]
then
pushd $dir
if [ -f composer.json ]
then
composer update
fi
popd
fi
done
Name this file composer-update.sh and place it in the WordPress root. After that run it from the terminal bash ./composer-update.sh
.
Conclusion
I thought that you should be able to update everything with one command. After finding out it doesn’t work that way, I found a way to make it work that way.