An unusually short article, for me, on basic WordPress plugin loader tricks.

Basic setup

Name the “loader” php file the same as the plugin directory.

Text Domain must match the directory name.

Avoid leading * on header lines = less bytes to process by the header processor in WordPress.

Ensure it runs from within WordPress

Use function_exists( ‘add_action’ ) instead of defined( ‘ABSPATH’).  It is more likely to be specific to WordPress.   It is also a better test as the loader calls the add_action function and will break if it is AWOL.

Not doing heartbeat processing

Short circuit to avoid loading the main plugin code if your plugin has zero influence on heartbeat operations.    WordPress heartbeats fire up AJAX requests every minute or two when a user is on the site.

Load on plugins_loaded

The plugins_loaded action loads early enough to be able to latch onto actions that have to happen in init or admin_menu. If your plugin requires others to be loaded this ensures that has happened, just make sure you set the action priority higher than the plugin you rely.

Put code another level down

Bury most of the PHP code at least another level deeper than the loader.  I prefer an include subdirectory but any name will do.   This helps the WordPress plugin processor run faster during major updates or when the plugin cache expires.     WordPress reads the first 8k header of all PHP files within the main directory when this happens looking for the Plugin Name etc. headstone.

Define your file

Using define( <plugin_dir>_FILE , FILE ) gives you a consistent and fast way to reference the plugin’s install directory.

I like to define <plugin_dir>_DIR as well based on this location and point it to the include subdirectory to make it easier to find and reference code classes and resource files like JavaScript or CSS files we need later.

I prefer defined( <def_var> ) || define( <def_var> , <value> ) which is cleaner and easier to read than if(){} constructs.

An example ‘loader’ file

See something wrong or have some other WordPress plugin loader trick to share?  Hit me up in the comments.

One Comment on “WordPress Plugin Loader Tricks

  1. Pingback: Why WordPress REST Performance Sucks - Lance Cleveland

Share Your Insight

%d bloggers like this: