# 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](https://www.forgewp.dev/docs/core/export-deployment/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?

> [!TIP]
> **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/**

```text
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
```

**Flowchart**

```mermaid
flowchart LR
  F["Flat *.php files"] -->|pasted into| B["backend.php"]
  D["src/ includes/ templates/ assets/"] -->|copied to| P["project/"]
  C["composer.json"] -->|composer install| V["project/vendor/"]
  B --> CP["Companion Plugin"]
  P --> CP
  V --> CP
  B --> T["The theme's built-in copy"]
  P --> T
  V --> T
```

- **Flat `*.php` files** 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 in `src/server/plugin/` is copied.

> [!WARNING]
> **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`:

**src/server/plugin/src/LicenseNumber.php**

```php
<?php
declare(strict_types=1);

namespace Acme\Licensing;

defined('ABSPATH') || exit;

final class LicenseNumber
{
    public static function format(int $n): string
    {
        return sprintf('ACME-%06d', $n); // ACME-000042
    }
}
```

> [!IMPORTANT]
> **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.

**wp.config.ts**

```ts
export default defineConfig({
  // ...your other settings
  companion: {
    autoload: { "Acme\\Licensing\\": "src/" },
  },
})
```

**3. Use it from a flat file**, and load the stylesheet:

**src/server/plugin/licensing.php**

```php
<?php
add_action('wp_enqueue_scripts', function () {
    wp_enqueue_style(
        'acme-receipt',
        FORGEWP_COMPANION_ACME_URL . 'assets/receipt.css'
    );
});

// [acme_license n="42"] in a post shows "ACME-000042"
add_shortcode('acme_license', function ($atts) {
    $n = (int) ($atts['n'] ?? 0);
    return esc_html(\Acme\Licensing\LicenseNumber::format($n));
});
```

### 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>_DIR` | The folder on disk, ending with `/` | `include FORGEWP_COMPANION_ACME_DIR . 'templates/receipt.php';` |
| `FORGEWP_COMPANION_<SLUG>_URL` | The 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`.

> [!TIP]
> **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.

1. Install Composer once from [getcomposer.org](https://getcomposer.org/download/).
2. In `src/server/plugin/`, create `composer.json` and add your library:

**Terminal (in src/server/plugin/)**

```bash
   composer require setasign/fpdi
```

3. Commit `composer.json` **and** `composer.lock`. Don't commit `vendor/`; 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).

> [!NOTE]
> **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_activated` | The plugin is activated, or the ForgeWP theme is activated while the plugin isn't | Create your database tables |
| `forgewp_companion_upgraded` | Once, on the first visit after you install a new version. Gets the old and new version | Change tables, move settings |
| `forgewp_companion_deactivated` | The plugin is deactivated | Stop scheduled tasks |
| `forgewp_companion_uninstall` | The plugin is deleted in wp-admin **and** the site owner opted in (below) | Delete your tables and options |

**src/server/plugin/licensing.php**

```php
<?php
add_action('forgewp_companion_activated', function () {
    acme_create_license_table();
});

add_action('forgewp_companion_upgraded', function ($from, $to) {
    if (version_compare($from, '1.2.0', '<')) {
        acme_add_buyer_column();
    }
}, 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.

> [!IMPORTANT]
> **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:
> 
> ```php title="wp-config.php"
> 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`:

**wp.config.ts**

```ts
companion: {
  exclude: ["assets/raw/**"], // source files of your images
},
```

## Requirements: other plugins and PHP version

If your code needs another plugin, say so. WordPress then refuses to activate the Companion Plugin without it:

**wp.config.ts**

```ts
companion: {
  requiresPlugins: ["easy-digital-downloads"],
  requiresPhp: "8.1",
},
```

The theme's built-in copy can't enforce this, so check in your code too, and tell the site owner what's missing:

**src/server/plugin/licensing.php**

```php
<?php
add_action('plugins_loaded', function () {
    if (!function_exists('edd_get_order')) {
        add_action('admin_notices', function () {
            echo '<div class="notice notice-error"><p>Licensing needs Easy Digital Downloads.</p></div>';
        });
        return;
    }
    \Acme\Licensing\Plugin::boot();
});
```

## 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:

**wp.config.ts**

```ts
companion: {
  embedInTheme: false,
},
```

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

**Terminal**

```bash
pnpm forgewp doctor
```

The **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](https://www.forgewp.dev/docs/core/export-deployment/companion-plugin) to install it next to your theme.

---

Source: [Writing Your Own Plugin Code](https://www.forgewp.dev/docs/core/export-deployment/companion-plugin-code)
