Writing Your Own Plugin Code
Ship your own PHP features in the Companion Plugin: folders, classes, Composer libraries, CSS and templates, setup on activation and upgrade, private files, and when a ready-made plugin is the better choice.
Sometimes a site needs a feature that no plugin offers exactly: a license number on every sold PDF, two extra fields in a booking form, a custom report. ForgeWP lets you write that feature as normal PHP code in your project. The export puts it into the Companion Plugin, so it keeps working when the site changes theme or runs decoupled.
This page shows how to organize that code, use PHP libraries, set things up when the plugin is activated or updated, and keep private files safe.
Plugin or your own code?
Use plugins for the platform, your own code for the glue
A mature WordPress plugin has years of fixes, security updates and support behind it. For payments, shops, SEO, backups, caching or spam protection, install the plugin. Write your own code for the small, project-specific parts that connect them: the extra rule, field or file a plugin does not do exactly the way your client needs.
A quick checklist before you write code yourself:
Question If yes Does a well-maintained plugin already do this? Install the plugin. Does the feature handle payments, passwords or personal data in a complex way? Prefer a plugin. You would have to maintain the security yourself. Is it a small addition to a plugin you already use (a field, an email, a stamp on a file)? Your own code is a good fit. Would a paid add-on cost more each year than a few hours of your time, plus updates? Your own code can be worth it. |
|---|
For example, the Hospitality 2035 project sells a study with Easy Digital Downloads (a plugin) and Stripe (a plugin). Only the license numbers and the PDF stamping are its own code.
Where the code goes
Everything lives in src/server/plugin/. There are two kinds of files:
src/server/plugin/
booking-fields.php ← "flat" files: small hooks, loaded in name order
licensing.php
src/ ← your PHP classes (one class per file)
includes/ ← other PHP files you load yourself
templates/ ← email or PDF layouts
assets/ ← CSS, JavaScript, images, fonts
composer.json ← optional: PHP libraries
composer.lock- Flat
*.phpfiles are joined into one file,backend.php. Use them for hooks:add_action(...),add_filter(...), registering routes. - The four folders are copied unchanged into a
project/folder of the plugin, and of the theme's built-in copy. Nothing else insrc/server/plugin/is copied.
No `namespace` or `declare` in flat files
PHP only allows namespace ...; and declare(strict_types=1); at the very top of a file. Flat files are joined into one, so they can't use either; the export stops and names the file. Put classes with a namespace into src/ instead.
A small example
Say you want a class that formats license numbers, and a stylesheet for the receipt page.
1. The class, in src/server/plugin/src/LicenseNumber.php:
1<?php
2declare(strict_types=1);
3
4namespace Acme\Licensing;
5
6defined('ABSPATH') || exit;
7
8final class LicenseNumber
9{
10 public static function format(int $n): string
11 {
12 return sprintf('ACME-%06d', $n); // ACME-000042
13 }
14}Every PHP file in a folder needs the `ABSPATH` line
Files in the plugin folder can be opened directly by URL. defined('ABSPATH') || exit; makes such a request do nothing. The export stops if a .php file in src/, includes/ or templates/ doesn't have it. Put it right after namespace (PHP doesn't allow it before).
2. Tell ForgeWP where the classes are, in wp.config.ts. This is how PHP finds Acme\Licensing\LicenseNumber without a require (autoloading). If you use Composer (below), Composer does this instead.
1export default defineConfig({
2 // ...your other settings
3 companion: {
4 autoload: { "Acme\\Licensing\\": "src/" },
5 },
6})3. Use it from a flat file, and load the stylesheet:
1<?php
2add_action('wp_enqueue_scripts', function () {
3 wp_enqueue_style(
4 'acme-receipt',
5 FORGEWP_COMPANION_ACME_URL . 'assets/receipt.css'
6 );
7});
8
9// [acme_license n="42"] in a post shows "ACME-000042"
10add_shortcode('acme_license', function ($atts) {
11 $n = (int) ($atts['n'] ?? 0);
12 return esc_html(\Acme\Licensing\LicenseNumber::format($n));
13});Reaching your files
Only one copy of the backend runs at a time: the plugin's when it is active, otherwise the theme's. Two constants always point at the project/ folder of the copy that runs:
Constant What it is Example use FORGEWP_COMPANION_<SLUG>_DIRThe folder on disk, ending with /include FORGEWP_COMPANION_ACME_DIR . 'templates/receipt.php';FORGEWP_COMPANION_<SLUG>_URLThe web address, ending with /FORGEWP_COMPANION_ACME_URL . 'assets/receipt.css' |
|---|
<SLUG> is your theme's slug from wp.config.ts, in capitals, with every character that is not a letter or digit turned into _. Slug acme gives FORGEWP_COMPANION_ACME_DIR; slug my-site gives FORGEWP_COMPANION_MY_SITE_DIR.
Don't use `__DIR__` or `plugins_url()` for your files
They point at a different place in the plugin and in the theme's copy. The two constants are always right.
PHP libraries with Composer
Composer is PHP's package manager, like npm for JavaScript. Use it when your code needs someone else's library, for example to edit PDF files.
- Install Composer once from getcomposer.org.
- In
src/server/plugin/, createcomposer.jsonand add your library:
composer require setasign/fpdi- Commit
composer.jsonandcomposer.lock. Don't commitvendor/; add it to.gitignore.
When you export, ForgeWP runs composer install --no-dev in a temporary copy (your project folder is not changed) and ships the result as project/vendor/. The libraries are loaded for you before your own code runs, so you can use them right away.
The export stops with a clear message when Composer is not installed, composer.lock is missing, or composer.lock no longer matches composer.json (run composer update to fix that).
Libraries that write files next to themselves
vendor/ is replaced on every plugin update, and some hosts make plugin folders read-only. If a library writes cache files into its own folder (tFPDF does this for fonts), point it at a writable folder of your own, such as your private folder (see below).
Setup when the plugin is activated, updated or removed
Add these hooks at the top level of a flat file, not inside plugins_loaded. They run in both copies of the backend.
Hook When it runs Typical use forgewp_companion_activatedThe plugin is activated, or the ForgeWP theme is activated while the plugin isn't Create your database tables forgewp_companion_upgradedOnce, on the first visit after you install a new version. Gets the old and new version Change tables, move settings forgewp_companion_deactivatedThe plugin is deactivated Stop scheduled tasks forgewp_companion_uninstallThe plugin is deleted in wp-admin and the site owner opted in (below) Delete your tables and options |
|---|
1<?php
2add_action('forgewp_companion_activated', function () {
3 acme_create_license_table();
4});
5
6add_action('forgewp_companion_upgraded', function ($from, $to) {
7 if (version_compare($from, '1.2.0', '<')) {
8 acme_add_buyer_column();
9 }
10}, 10, 2);forgewp_companion_upgraded compares with the version in wp.config.ts, so raise that number with each release. It doesn't run on the very first install; use forgewp_companion_activated for that.
Deleting the plugin keeps your data unless the owner opts in
Orders, license records and settings are easy to lose by accident, and the theme's built-in copy keeps using them after the plugin is deleted. So forgewp_companion_uninstall only runs when wp-config.php contains:
define( 'FORGEWP_COMPANION_DELETE_DATA', true );
Keep private files out of the plugin
Everything inside a plugin folder can be downloaded by anyone who guesses the address. Never put files you sell, or customer files, in src/server/plugin/.
- Store them outside the web folder, if your host allows it, for example in a folder next to the WordPress folder:
dirname(ABSPATH) . '/acme-private'. Nobody can reach that by URL. - Otherwise use a folder in
wp-content/uploads/that the web server refuses to serve. - Deliver them through your own PHP code that first checks the visitor may have the file (for example, that the order is paid).
ForgeWP never copies these files, wherever they are in your plugin folders: .env files, *.key, *.pem, auth.json, tests/, node_modules/, Git files, phpunit.xml, and Markdown files. Add your own patterns with companion.exclude:
1companion: {
2 exclude: ["assets/raw/**"], // source files of your images
3},Requirements: other plugins and PHP version
If your code needs another plugin, say so. WordPress then refuses to activate the Companion Plugin without it:
1companion: {
2 requiresPlugins: ["easy-digital-downloads"],
3 requiresPhp: "8.1",
4},The theme's built-in copy can't enforce this, so check in your code too, and tell the site owner what's missing:
1<?php
2add_action('plugins_loaded', function () {
3 if (!function_exists('edd_get_order')) {
4 add_action('admin_notices', function () {
5 echo '<div class="notice notice-error"><p>Licensing needs Easy Digital Downloads.</p></div>';
6 });
7 return;
8 }
9 \Acme\Licensing\Plugin::boot();
10});Without the theme's built-in copy
By default the theme carries a copy of the backend, so a site works with the theme alone. With big libraries, or for a theme going to the WordPress.org directory (which doesn't accept themes with plugin features), you can turn that off:
1companion: {
2 embedInTheme: false,
3},The theme then needs the Companion Plugin. Until the plugin is active, visitors see a "Site temporarily unavailable" page (so search engines come back later), and wp-admin shows a notice asking to install it.
Check before you export
pnpm forgewp doctorThe Companion Plugin Sources check finds the same problems the export would stop on: flat files with namespace or declare, PHP files without the ABSPATH line, a missing composer.lock, or Composer not being installed.
Continue with The Companion Plugin to install it next to your theme.