Wp plugin bootstrap

From Lonsdale201/wp-agent-skills · View interactive version

Wp plugin bootstrap is an AI agent skill from the GitHub repository Lonsdale201/wp-agent-skills. Scaffolds and reviews the main entry-point PHP file of a WordPress plugin — header (with Requires Plugins for WP 6.5+), ABSPATH guard, file/path/url/version constants, Composer PSR-4 autoload with `src/` as the default class root, optional scoped fallback for release ZIP safety, PascalCase class fil

How to use this skill

Skill file

WordPress plugin: bootstrap (main file)

The single PHP file at the plugin root, named after the plugin folder, that WordPress loads first when the plugin is active. Get this right and the rest of the plugin can be a clean class-based architecture; get it wrong and you ship a plugin that fails activation, leaks runtime errors, or won't update cleanly.

This skill covers ONLY the entry-point file and the immediately-adjacent decisions (composer.json, optional uninstall.php reference). Activation cleanup, deactivation cron clear, custom uninstall logic — those are scope for wp-plugin-lifecycle (sibling skill).

When to use this skill

Trigger when ANY of the following is true:

The diff or file most likely contains: a Plugin Name: header, register_activation_hook, register_deactivation_hook, spl_autoload_register, defined('ABSPATH'), plugins_loaded, Requires Plugins, or a composer.json at the plugin root.

Hook firing order

Core loads active plugin files after muplugins_loaded, then fires

plugins_loaded, after_setup_theme, and init. Two practical rules:

Read references/bootstrap-contracts-and-mistakes.md for the verified sequence

and review examples.

Anatomy of a clean bootstrap file

<?php
/**
 * Plugin Name:       My Plugin
 * Plugin URI:        https://github.com/you/my-plugin
 * Description:       What this plugin does, in one sentence.
 * Version:           1.0.0
 * Requires at least: 6.5
 * Requires PHP:      8.0
 * Requires Plugins:  jetformbuilder
 * Author:            Your Name
 * Author URI:        https://github.com/you
 * License:           GPL-2.0-or-later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       my-plugin
 * Domain Path:       /languages
 */

declare(strict_types=1);

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

define( 'MYPLUGIN_VERSION', '1.0.0' );
define( 'MYPLUGIN_PLUGIN_FILE', __FILE__ );
define( 'MYPLUGIN_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
define( 'MYPLUGIN_PLUGIN_URL',  plugins_url( '/', __FILE__ ) );

const MYPLUGIN_MIN_PHP = '8.0';
const MYPLUGIN_MIN_WP  = '6.5';

// Autoloader — Composer first, optional scoped PSR-4 fallback for ZIP installs.
$autoload = MYPLUGIN_PLUGIN_PATH . 'vendor/autoload.php';
if ( file_exists( $autoload ) ) {
    require $autoload;
}

spl_autoload_register( static function ( string $class ): void {
    $prefix = 'MyPlugin\\';
    if ( 0 !== strpos( $class, $prefix ) ) {
        return;
    }
    $relative = substr( $class, strlen( $prefix ) );
    $file     = MYPLUGIN_PLUGIN_PATH . 'src/'
        . str_replace( '\\', '/', $relative ) . '.php';
    if ( file_exists( $file ) ) {
        require $file;
    }
} );

register_activation_hook( __FILE__, static function (): void {
    $errors = myplugin_requirement_errors();
    if ( ! empty( $errors ) ) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
        deactivate_plugins( plugin_basename( __FILE__ ) );
        wp_die(
            wp_kses_post( implode( '<br>', $errors ) ),
            esc_html__( 'Plugin activation failed', 'my-plugin' ),
            array( 'back_link' => true )
        );
    }
} );

function myplugin_requirement_errors(): array {
    $errors = array();
    if ( ! is_php_version_compatible( MYPLUGIN_MIN_PHP ) ) {
        $errors[] = sprintf(
            'My Plugin requires PHP %s or higher. Current: %s.',
            MYPLUGIN_MIN_PHP,
            PHP_VERSION
        );
    }
    if ( ! is_wp_version_compatible( MYPLUGIN_MIN_WP ) ) {
        $errors[] = sprintf(
            'My Plugin requires WordPress %s or higher.',
            MYPLUGIN_MIN_WP
        );
    }
    return $errors;
}

add_action( 'plugins_loaded', static function (): void {
    \MyPlugin\Plugin::instance( MYPLUGIN_PLUGIN_FILE );
} );

That single file is the entire entry-point. Everything else lives in src/ under the MyPlugin\ namespace, autoloaded. A class named MyPlugin\Folders\FolderService lives in src/Folders/FolderService.php, not includes/class-folder-service.php.

Critical rules

1. Header fields that matter in 2026

The authoritative list is parsed by get_plugin_data(). Core needs `Plugin

Name` for discovery; other headers drive compatibility, dependencies, updates,

i18n, attribution, and directory review. Read

references/bootstrap-contracts-and-mistakes.md for the field matrix.

WordPress 7.1 makes get_file_data() recognize a header line prefixed by either

<?php or the short open tag <?. This is parsing compatibility, not a new

recommended bootstrap style: keep the standard <?php opening tag and a normal

comment header. Do not use the parser change to justify short open tags, mixed

template syntax, or executable expressions inside metadata.

2. Composer + `src/` PSR-4 is the modern default

Composer + PSR-4 autoload is the right choice for any non-trivial plugin in 2026: predictable namespaces, dependency management, dev-only tooling separation (PHPStan, php-cs-fixer), updater libraries vendored cleanly. Treat it as the strongly recommended baseline.

Use src/ as the default class root and PascalCase filenames that match class names. This is the baseline shape:

my-plugin/
├── composer.json
├── my-plugin.php
├── src/
│   ├── Plugin.php
│   ├── Schema.php
│   ├── Setup/Activator.php
│   ├── Setup/Deactivator.php
│   ├── Folders/FolderService.php
│   └── Rest/FoldersController.php
└── assets/

Do not scaffold includes/class-my-plugin.php, includes/class-folder-service.php, or WPCS-era class filenames for a new Composer plugin. Those are legacy migration targets, not the default architecture.

Users who install from GitHub directly without composer install, or from a ZIP without vendor/, will get fatal errors unless the release artifact is built correctly. Prefer:

A composer.json minimum:

{
    "name": "you/my-plugin",
    "description": "What this plugin does.",
    "type": "wordpress-plugin",
    "license": "GPL-2.0-or-later",
    "require": {
        "php": ">=8.0"
    },
    "autoload": {
        "psr-4": {
            "MyPlugin\\": "src/"
        }
    }
}

Plus composer install, commit composer.lock, gitignore vendor/, ship vendor/ inside release ZIPs, and use composer dump-autoload -o in the release/build step.

3. `Requires Plugins` since 6.5 — use it, but understand the limits

Add the dependency at the plugin header level:

Requires Plugins: jetformbuilder, woocommerce

WP surfaces missing dependencies on the plugins screen and prevents activation when they're absent (see wp-includes/class-wp-plugin-dependencies.php). This is layered enforcement — also keep your runtime requirements check (Section 4) because users on older WP, sites that bypass validate_plugin_requirements(), or upgrade scenarios can still get past the header check.

Limits to know:

4. Activation hook = one-shot setup, NOT runtime config

register_activation_hook( __FILE__, $callback ) fires once per activation event — including reactivations. It does NOT fire on plugin updates (use upgrader_process_complete for that).

Inside the hook:

DO NOT inside the activation hook:

5. Direct-access guard

Top of every PHP file (bootstrap AND class files):

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

Class-only files don't crash without it (no top-level execution), but it's a wp.org submission expectation and a defense-in-depth habit. Three lines, zero downside.

6. Text-domain — what actually loads a bundled `.mo`

Nothing auto-discovers a plugin's own languages/ folder by convention. The

global location (wp-content/languages/plugins/my-plugin-<locale>.mo) is

searched on every supported version. A bundled translation is registered

from the plugin header only on WP 6.8 and up — from Domain Path, or the

plugin root when that header is absent. On 6.7 and earlier nothing looks

inside the plugin folder, so a bundled .mo silently never loads without an

explicit load_plugin_textdomain() call. Domain Path is load-bearing, not

decoration: omit it and even 6.8+ registers the plugin root, leaving a

languages/ subfolder invisible.

Do not translate values during plugin-file load, plugins_loaded, or

activation. Read the i18n section in

references/bootstrap-contracts-and-mistakes.md before adding

load_plugin_textdomain() or diagnosing an early-translation notice.

7. The bootstrap file does NOT contain business logic

It contains: header, ABSPATH guard, constants, autoload, activation/deactivation hook registrations, the plugins_loaded instantiation. Maybe 100-200 lines.

It does NOT contain: classes, business logic, hook callbacks beyond bootstrap, custom helper functions used elsewhere, asset enqueueing. All of those belong in dedicated class files under src/.

If you find a bootstrap file pushing 400+ lines, move logic out. The bootstrap is a launcher, not the engine.

Composer-free path (legacy/minority)

If Composer is unavailable, preserve the same namespace-to-src/ and

PascalCase filename convention with a plugin-scoped autoloader. See the

reference for the trade-off; do not revive class-*.php for new code.

Common mistakes

Read references/bootstrap-contracts-and-mistakes.md when reviewing dependency

calls, early translations, requirements, class placement, header spelling, or

autoload scope.

Cross-references

What this skill does NOT cover

References

references/bootstrap-contracts-and-mistakes.md.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.