A WordPress Plugin Coding Adventure – A Love Hate Relationship

Over the past 48 hours I spent time between numerous meetings writing another WordPress Plugin, a WooCommerce Report Modifier that we need for our Store Locator Plus store.   I’ve not written a “new from scratch” plugin that was not related to the Store Locator Plus system for quite some time.    It gave me a new perspective on the entire WordPress plugin coding adventure.

Open Source Is Great

One of the biggest things I re-affirmed about coding plugins for WordPress is that I LOVE open source.   As a developer this love for open source has NOTHING to do with price.    I don’t love it because the prices of open source are often lower than “regular” software; in face I think that is on of the biggest problems with open source is the stigma … or general idea that users THINK… the products should be free or darn-near it.    What I love is that I can both FIX things and SEE HOW THEY WORK.     The fixing and the seeing were both key elements in being able to create a plugin that did what I needed in just over a day versus weeks or months waiting for the people at WooCommerce to do something for me.

Starting A  Plugin Is Easy

I also realized that despite my difficulties in writing my first plugin years ago, the entire process is actually fairly easy and does not to be as complicated as many people make it out to be – even when using well defined classes in place of procedural code (please, please , please do NOT write your plugins using “inline” or procedural code).   For a private plugin you don’t even need to create a readme.txt file.   Create a directory in the plugins folder of WordPress, name a file the same thing as the directory with a .php extension and add a few lines of code.

Since I could read the original source of WooCommerce I knew exactly which hook I needed to invoke and whipped up the first function in a few minutes.

Hooks and Filters Are Paramount

Speaking of hooks, learn about them and USE THEM.   Implementing WordPress hooks and filters is critical to properly augmenting anything in WordPress.   Since most well-crafted plugins, including my Store Locator Plus base plugin and add on packs,  and themes also sprinkle hooks liberally throughout their code.    In my case I could find a WooCommerce hook that allowed me to modify the product report without messing with the original code from WooCommerce.      Since  WooCommerce was open source I could read the report-generating code and find the exact hook I needed within minutes.   Very nice.

Plugins and Plugin Components Are Not Created Equal

In the bad category, I was reminded almost immediately that not all plugins or plugin modules are created equal.  WooCommerce is a beast that has lots of code with lots of modules written by different authors and includes obsolete elements and dead-ends; much like Store Locator Plus.   This means that outdated practices are built into the code as are some algorithms that were created during the “hey, I’m learning WordPress coding” phase of plugin development.   Typically that means little-or-no ability to modify that piece of code and change how it works because there are NO hooks or filters to tap into.   Boo!

Inconsistent Plugin Architecture = More Plugins

The lack of hooks and filters is true with MANY of the WooCommerce native elements like the Customer List report or Orders search interface.     That meant recreating an exact copy the Customer List I wanted to modify and adding in hooks, filters, and feature to my “Extended Customer List” report.   That means I have a plugin that shares 70% of the Customer List coding from the WooCommerce product which in turn means my live site now has over 100 lines of code installed that should never have been necessary.    Multiply that by the 48 plugins I need to run my site properly.

More plugins = more bloat = more maintenance and security issues.

The lack of a true coding standard for plugin developers , or maybe it is a training issue, causes a LOT of repeat work in the WordPress plugin ecosystem.

Documentation Is Inconsistent

As you delve deeper into the WordPress plugin coding world you soon realize not all documentation is created equal.   Some WordPress functions are well documented internally and externally with full phpDoc comments a presence on the “old and outdated” Codex and on the “new and improved” WordPress Code Reference.  Many functions, however are incomplete at best with no examples and little-or-no community knowledge on the WordPress Code Reference site.   Often you end up jumping back to the older Codex site.    In some cases, rather infrequently with WordPress Core, you find functions or classes that are not even listed or documented on EITHER site or if they do appear through the coding “fu” on the WCR they have zero useful information thanks to the lack of proper phpDocs.    In the end you read code and trace execution (thank you again Open Source).

Plugins are exactly like that but worse.  Many, including the super-popular WooCommerce plugin, have sparse-if-any online documentation on CODING for the product.   Almost NONE have any easy way to ferret out those hooks and filters.  You always end up spending time tracing code execution to find those “nuggets of knowledge”.

Contributing Code Is Futile

Well, mostly futile.    If you code plugins or themes for long enough you will find a bug in SOMEONE ELSE’S CODE.    Most organizations have a way to report the bug and contribute your patches to fix the bug back to them so they can improve their products.   Most organizations take their sweet time getting around to it.  Often your patches never get put in place.

My personal experiences: Store Locator Plus was born from over 100 patches to a plugin that were submitted to the author but never integrated despite a few-dozen emails to the author.  In fact the response was “I’m on haitus”.  For over a YEAR.      My original fixes to dbDelta, admittedly a critical component of WordPress that warrants extra care-and-attention, took OVER TWO YEARS to finally make it into core.   Patches to bbPress and over a dozen other lesser-known plugins were never even looked at.   WooCommerce?  We’ll wait and see.

It would sure be nice if plugins, especially those hosted on the WordPress Plugin Directory, had a formal and consistent patch submission system.   Even better, a community “vote” to allow a “master of all plugins” to accept the patches on behalf of a MIA plugin author.   I’d check off the “allow WordPress Plugin Team to integrate patches” on my repo.

Internal Use Only Components Are Bad

WP_List_Table.    It has been clearly marked as “for internal use only”.    Yet nearly any significant plugin out there is running a class that extends it.     Which is fine except you are NOT SUPPOSED TO DO THAT according to WordPress.  You are supposed to clone the entire class (more duplicate code – see above) and build off of that.

Yes, I get why that is, but that kills one of the key concepts that makes WordPress great – the ability to extend and augment with hooks and filters not copies-and-hacks.

PHP Versions Are  A Pain

The WordPress Plugin Team announced, just yesterday, that you should run PHP 7 lint against your code.  VVV runs PHP 5.5.  WordPress itself says PHP 5.2 is fine.   Most hosting companies are running PHP 5.5 or lower.

When you code using a version of PHP newer than 5.2, as I do on my VVV box, you have a high risk of creating a plugin that passes all testing but as soon as someone runs it on PHP 5.4 it crashes.  Hard.

<!– start sidebar –>
WordPress must set a baseline standard for PHP.  If it is 5.2 that’s fine.   You cannot have your plugin team recommending PHP7, your core team recommending a development environment that defaults to 5.5, and  tell hosting companies PHP 5.2/3/4 are fine.

    
IMO WordPress needs to set the standard to PHP5.6 which they ‘recommend’ but do not require.   When 28% of the Internet is using your technology you can dictate what version of PHP is running nearly everywhere.
<!– end sidebar–>

Overall It Is A Good System

In general the system WordPress has  in place for plugin development is pretty darn good.  I think it is one of the biggest reasons WordPress has gained market share and has so many plugins available.     The system needs work.  The code needs work.    But in reality, what big world-changing products don’t need to evolve on a continual basis.

At the end of the day I could get what I wanted to accomplish done in just over a day.    I have my new report of customers that I can export to a CSV file, sort, hide columns and do all of the things I needed to get a project done.  (BTW, I’ve posted my WooCommerce Report Modifier on my store in case anyone else wants to check it out.)

Open source made that possible.  At the end of the day that is the BEST argument for why I think Open Source is the best option for releasing software.   Now if we can just convince the consumers that it is worth MORE TO THEM than closed-source system.   Open Source software should be priced HIGHER than other solutions not “Nearly Free”.

More Notes On PHP Version Switching in VVV

This article is a follow-on to Changing PHP Version on Vagrant .

Here are some discoveries of using different versions of PHP on vagrant.

Change Your Host

The default vvv installation has the db_host set to ‘localhost’ in the wp-config.php file.

phpbrew, however, sets the default db listener to 127.0.01 explicitly.   They do not want to change it as they claim “this is the proper default”.   As happens often with technology gurus both the VVV camp and the phpbrew camp claim to be “right” in the purist-interpretation of the technology “bible”, after 30 years I’ve still not received my copy BTW.  The bottom line is that if you change your VVV PHP version using phpbrew you’ll need to edit your wp-config.php and change your db_host to be defined as 127.0.0.1

You will want to do this for each WordPress branch you are working with: wordpress-default , wordpress-develop, wordpress-trunk.

These directories are stored locally on your host so you can, theoretically, change them by going to your local vvv install directory and finding the www subdirectory and the proper wordpress-default directory under that.

Check Your nginx Config

The default listener for nginx php connections is defined in the /etc/nginx/nginx.conf file on the guest (where you are after you login with vagrant ssh).

Look for the entry ending with .sock in the upstream php section.   This defines the default compiled php version that is linked to nginx.  This will be what is run whenever someone accesses a PHP file from the nginx browser (the default for vvv).

Change this manually be commenting out the default server line and adding a new socket listener for your default phpbrew path.

If you run the vagrant provision command, this file will be created from your local HOST (not the guest box) and will overwrite things you do here.  You can make it persistent by editing your ~/config/nginx-config/nginx.conf file on your HOST box (where you installed vvv not after a vagrant ssh command).

Restart nginx After Socket Changes

If you use phpbrew to build a new version of PHP and edit the nginx.conf file to use the new PHP listener you just built and started with php fpm start, restart nginx.

phpMyAdmin Will Be Broken

phpMyAdmin uses its own configuration files to connect to MySQL.  You will need to change the default phpMyAdmin configuration file to point to 127.0.0.1 instead of localhost to connect.

I’ve not yet found that config setting on vvv, but when I do I’ll let you know.   If you know the trick ,please comment or email me via lance at this website.

Investigate Docker

As a fellow tech guy and past colleague said “sounds like you need Docker”.   Yeah, probably so.  For most people not doing WordPress Core contributions, Docker is likely a much better solution for switching PHP versions.  If all you need is a place to run a local WordPress install and build themes / plugins that will likely be far easier (and faster) than VVV.

However I do contribute to core when I can and that requires me to have trunk, dev, and local installs of WordPress so I can build current patch files AND test with my plugins.    Can I do that in Docker?  Sure, but I’m guessing it is more work.   I’m also certain that at the next WordCamp the core team can help me if I’m running VVV as they often cite this as the way to “get started”.

Maybe I’ll play with Docker if I ever get a free afternoon and write some articles on doing WP Core development on that.

Someone also mentioned on my Twitter feed that Pressmatic may help (a Docker front end for OSX).  Looks cool and may be worth investigating someday.

Changing PHP Version On Vagrant


After nearly 24 hours of working on this issue I finally figure out how to change the running version of PHP from the WEB SERVER under VVV for my WordPress development environment.  I recall, at a WordPress conference last year, someone touting how easy it was to change PHP versions to test plugin and theme development on various deployment stacks.    Sure, if you happen to want to pull a whole new box image with just the right version of PHP along with all your other tools in place.

For me, I wanted to keep my vanilla Vagrant box with a single mapped directory intact.   I wanted the SSL certificates I created to remain as well, which was another day-long project.   The only thing I wanted to do was replace the default PHP 5.5 release with PHP 5.4.43 to match that of a client.  I’d also like to test with PHP 5.2 someday as that is the minimum supported version for WordPress.

It turns out that changing the PHP version at the command line is easy.   Making it take affect in nginx, the default web server for VVV, is a whole other story.  I found lots of resources on doing this “simple trick” but very few were current and almost ALL were missing information or provide cryptic installs such as “on Apache” (not the VVV default web server) or “on Debian” (no the VVV default distro).

The Summary

Install and use phpbrew to build the PHP flavor you are looking for.

Find your particular flavor of PHP under the vagrant user directory and get the path to the socket listener.

Modify the nginx configuration file to use the socket for your flavor of PHP.

Restart nginx.

Installing phpbrew

Install phpbrew either by going to the phpbrew site and following their instructions OR go to the Vagrant site , install Vagrant, and then clone the repo to a local directory.    After cloning the repo checkout the feature/phpbrew branch.   phpbrew will be installed and ready-to-run.

I chose the “install manually” option as I wanted to keep my Customfile and some tweaks to my config files that I already had in place on my current “non-repo based” Vagrant box.

Make sure you run the phpbrew init command, preferably as the default vagrant login NOT as root.  This will create a hidden .phpbrew directory under your user’s (vagrant) home directory (/home/vagrant).

Install Your PHP “Flavor”

Decide what version of PHP you want to run and install it with phpbrew.  This may take a little time.   When it is done  you should have some new directories under your /home/vagrant/.phpbrew/php folder for the version you installed.

You will want some default options as well.   Here is my command for PHP 5.4.43 with the default configuration, FPM support, MySQL support, and CLI support.

Find The Socket Listener

Under the ~/.phpbrew/php//etc directory you will find the configuration files for that version of PHP.    Search the files for the line that loads the socket listener.  The socket listener ends with .sock and is usually in a /run/ directory.     I use grep to search:

The part after the listen = that is returned is the patch to the PHP 5.4.43 socket listener for FPM.

Modify The nginx Config

I edited this directly on my guest box by logging in with vagrant ssh and restarted nginx.  The default config file is at /etc/nginx/nginx.conf

Look for the line that loads the current socket listener, usually in the /var/run directory and comment it out.  Put another line in that points to your specific PHP listener.   Here is my snippet pointing to my PHP 5.4.43 version:

The other option to make this more permanent is to edit the vagrant config files.  Got to the directory that contains your Vagrant environment, the place with the Vagrantfile, and go to the ./config/nginx-conf/ subdirectory.   Edit the nginx.conf file.     This is the file that will build the /etc/nginx.conf file whenever you provision your Vagrant box.    If you change this file you will want to run vagrant provision from your host.

Restart nginx

Again, I did this from the command line on my vagrant box after logging in with vagrant ssh.

Check Your Work

Go to to your web browser and check the phpinfo status.

By default this is found at http://vvv.dev on your host.

Click the phpinfo link.

vvv dev dashboard

vvv dev dashboard

Using PHP Anonymous Functions In WordPress

Recently I published an article “Adding WordPress REST API Security To Basic CRUD Operations” where the permissions callback points directly to a function:

This style of defining a function call is known in PHP as an anonymous function.   The example is based on an example provided by the WordPress REST API documentation.   The problem with such a method is that it is not supported on older versions of PHP;  the anonymous function was introduced in PHP 5.3.  To exacerbate the problem, WordPress recommends PHP version 5.6 but will run on PHP version 5.2.4.    As such many hosting companies opt to take the path of least-effort and run the oldest version of PHP they can.  That means they are running PHP 5.2.4.

Guess what happens when a customer runs your plugin or theme that uses anonymous functions on PHP 5.2.4?  It breaks.

How do you fix the issue?

Use named functions.   Anywhere you use an anonymous function you can use a named function.    In the example above we can convert the anonymous function to a method within the class that is setting up our REST route:

 

Adding WordPress REST API Security To Basic CRUD Operations

Work has been underway adding REST API functionality to the Store Locator Plus plugin.   Most people are familiar with the basic concept of using REST to fetch data from a remote server.   We use this every day when surfing the web using the basic premise of an HTTP GET protocol.   In short this is the simplest form of a REST “read” operation.   Go here, get this thing and show it to me.

REST APIs get more exciting when  you talk about adding basic create/update/delete operations proving the full CRUD functionality via the REST protocol.    The issue with using REST for these operations , especially via the WordPress REST API , is that you are now exposing your data via  service that anyone with even a touch of technical prowess can now create, update, or delete data elements from your site.     In the case of our locator plugin, we don’t want any random person to send a simple HTTP request to our server and delete a location.

The WordPress REST API provides a simple mechanism for adding security to these types of requests.   It uses the built-in WordPress user authentication and roles-and-capabilities to ensure a user has permission to alter the specific object, in our case location data, before handling the REST request.   To employ this security you will need two things;  A plugin that manages authentication requests  and the addition of a permission_callback parameter to your register_rest_route() call within your plugin/theme class that is managing your REST API.

The first part, adding a plugin, is easily handled by fetching one of the git repositories listed at the WordPress REST API documentation site.   You can choose either Basic Authentication (very weak security) or oAuth (much better option).   Using Basic Authentication is great for development and is what I use when testing RESTful services via phpStorm 2016 with its built-in RESTful service applet.

The second part, adding a permission_callback parameter, is done in the coding of your plugin or them that is managing your REST requests.   This can be handled using a simple anonymous function that returns the results of the WordPress current_user_can() function.     In Store Locator Plus we check to make sure the the user, authenticated with one of the above plugins as part of the source of the REST request, has the capability  of ‘manage_slp_user’ assigned.   By default this is assigned to all admin users when Store Locator Plus is installed.   The register_rest_route call looks like this:

This setup will check that the REST request has passed authentication and that the user identified with the request has the manage_slp_user capability before executing the add_location method in our REST API class.

Adding security on your POST/PUT/PATCH REST requests is as simple as that.

There are a lot of other tricks built into the WordPress REST API. Keep track of this blog to watch for more articles on WordPress development as I share what I’ve learned each week.

%d bloggers like this: