abuyoyo/plugincore

WordPress插件核心帮助类

0.31 2024-06-22 00:00 UTC

This package is auto-updated.

Last update: 2024-09-22 02:16:48 UTC


README

WordPress插件注册的帮助类。

插件模板和模板生成器很麻烦。它们施加的文件结构太繁琐(且冗余),无法应用于每个插件。WPHelper\PluginCore通过一个简单的类(通常隐藏在您的vendor/目录中)替换了模板。

如果您需要,可以使用 WPHelper\AdminMenuPage 来注册和生成管理菜单。

要求

安装

使用 Composer 安装,或者只需将PluginCore.php文件放入您的插件文件夹中并引入它。

// Require the Composer autoloader anywhere in your code.
require __DIR__ . '/vendor/autoload.php';

或者

// Require the class file directly from your plugin.
require_once __DIR__ . 'PluginCore.php';

WPHelper\PluginCore使用 PSR-4 自动加载。

基本用法

WpHelper/PluginCore替换了众多插件核心骨架生成器。只需在插件文件顶部添加这些代码行即可。

WpHelper/PluginCore将为您的代码定义%PLUGIN%_BASENAME、%PLUGIN%_PATH、%PLUGIN%_URL、%PLUGIN%_FILE常量。

/*
 * Plugin Name: My Awesome Plugin
 * Description: Plugin's description.
 * Version:  1.0.0
 */

// Import PluginCore.
use WPHelper\PluginCore;

// Register the plugin
$args = [
    'title' => 'My Awesome Plugin', // Optional - will fallback to plugin header Plugin Name.
    'slug' => 'my-awesome-plugin', // Optional - will generate slug based on plugin header Plugin Name
    'const' => 'MYPLUGIN' // Optional - slug used to define constants: MYPLUGIN_DIR, MYPLUGIN_URL etc. (if not provided will use 'slug' in ALLCAPS)
    'activate_cb' => 'activate_callback' // Optional - Provide a callable function to run on activation
    'deactivate_cb' => 'deactivate_callback' // Optional - Provide a callable function to run on deactivation
    'uninstall_cb' => 'uninstall_callback' // Optional - (@todo) Consider using uninstall.php and not this plugin. This plugin can run in the global scope and cause problems
];

// Setup plugin constants and activation/deactivation hooks
new PluginCore( __FILE__, $args );

// Start writing your code here..
include '/foo.php';
add_action( 'plugins_loaded' function() {
    // whatever..
});

常量

WPHelper\PluginCore在您的代码中定义了常量。其中__FILE__是提供给类的文件名,%PLUGIN%'const'选项。如下所示

define( '%PLUGIN%_URL', plugin_dir_url( __FILE__ ) );
define( '%PLUGIN%_FILE', __FILE__ );

这是WPHelper\PluginCore定义的常量。有一些冗余是为了适应不同的约定。

  • %PLUGIN%_PATH: plugin_dir_path( __FILE__ ) )
  • %PLUGIN%_DIR: plugin_dir_path( __FILE__ ) )
  • %PLUGIN%_URL: plugin_dir_url( __FILE__ ) )
  • %PLUGIN%_BASENAME: plugin_basename( __FILE__ ) )
  • %PLUGIN%_FILE: __FILE__
  • %PLUGIN%_PLUGIN_FILE: __FILE__

获取实例

您可以使用静态方法get()和插件短名在任何地方引用所有PluginCore实例。在plugins_loaded钩子或之后可用。

PluginCore::get('my-awesome-plugin'); // returns PluginCore instance constructed with slug 'my-awesome-plugin'