Skip to content
Miguel Muscat edited this page Nov 30, 2022 · 5 revisions

1. Install the SDK

composer require rebelcode/wp-plugin-sdk

2. Create a Plugin instance

The Plugin instance is the main entry point when using the SDK. It is responsible for managing the modules, and acts as a proxy for the DI container.

To create a plugin instance, simply call the static factory method in your plugin's main file.

/**   
 * @wordpress-plugin
 * Plugin Name: My Plugin
 * Version: 0.1
 */
use RebelCode\WpSdk\Plugin;

$plugin = Plugin::create(__FILE__);

This will automatically load the plugin's modules from the modules.php file in the plugin's root directory.

3. Running the plugin

To run your plugin, call the run() method on the plugin instance.

$plugin->run();

This will run all the plugin's modules.

⚠️ Do not run the plugin from within a WordPress hook. This method should be run directly from within the file scope.

4. Add your modules

Create a modules.php file in the root directory of the plugin. From this file, return an associative array of module instances. The keys in the array should be the unique IDs for each module.

// modules.php

return [
    'my_cpt' => new MyCptModule(),
    'admin_page' => new AdminPageModule(),
    'settings' => new SettingsModule(),
];

For more information on modules, see the Modules documentation.

Recommended Setup

The recommended setup for a plugin's main file is as follows:

  • Check if the plugin is running in a WordPress environment. If not, exit.
  • Load the Composer autoloader, if it exists.
  • Check if the autoloader was loaded. If not, exit.
  • Create a function that returns the singleton instance of the plugin.
  • Run the plugin.
/**   
 * @wordpress-plugin
 * Plugin Name: My Plugin
 * Version: 0.1
 */
use RebelCode\WpSdk\Plugin;

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

// Include the Composer autoloader, if it exists.
// (it may be missing if the WordPress plugins are managed via Composer,
// such as when using Bedrock)
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
    require_once __DIR__ . '/vendor/autoload.php';
}

// Ensure that the autoloader is actually loaded before continuing.
if (!class_exist(Plugin::class)) {
    return;
}

// Singleton instance of the plugin.
function myPlugin() {
    static $plugin = null;
    return $plugin ?? $plugin = Plugin::create(__FILE__);
}

// Run the plugin.
myPlugin()->run();

Next Steps