wedevs/wp-utils

为WordPress提供的各种类和特性

v1.1 2023-06-06 13:28 UTC

This package is auto-updated.

Last update: 2024-09-06 16:10:05 UTC


README

License: LGPL v3 Packagist GitHub all releases Packagist Downloads

WordPress插件开发的有用代码和工具集合。这些代码简化了常见任务,并在WordPress项目中促进了代码的可重用性。

安装

使用Composer安装包

composer require wedevs/wp-utils

用法

ContainerTrait

使用ContainerTrait可以在您的类中轻松存储和检索动态属性,提供了一种灵活方便的方式来管理和访问数据,而无需显式定义类属性。

用法示例

use WeDevs\WpUtils\ContainerTrait;

class MyPlugin {

    use ContainerTrait;

    public function __construct() {
        // Register an instance
        $this->my_service = new MyService();

        // Use the instance
        $this->my_service->doSomething();
    }

    // Rest of your plugin code...
}

HookTrait

HookTrait 提供了在您的插件中管理WordPress操作和过滤钩子的可重用方法。它简化了添加、删除或执行钩子的过程。

use WeDevs\WpUtils\HookTrait;

class MyPlugin {

    use HookTrait;

    public function __construct() {
        // Add an action hook
        $this->add_action( 'init', 'my_init_function' );

        // Add a filter hook
        $this->add_filter( 'the_title', 'my_title_filter' );
    }

    public function my_init_function() {
        // Actions to be performed during 'init'
    }

    public function my_title_filter( $title ) {
        // Modify the post title
        return $title . ' - Customized';
    }

    // Rest of your plugin code...
}

LogTrait

LogTrait 为您的WordPress插件提供了一个简单的日志记录机制。它允许您将消息记录到PHP错误日志。

用法示例

use WeDevs\WpUtils\LogTrait;

class MyPlugin {

    use LogTrait;

    public function some_method() {
        // Log an informational message
        $this->log_info( 'Some informational message.' );

        // Log an error message
        $this->log_error( 'An error occurred.' );

        // Log a debug message
        $this->log_debug( 'A debug message' );
    }

    // Rest of your plugin code...
}

SingletonTrait

SingletonTrait 为您的WordPress插件类实现了单例模式。它确保只创建一个类的实例,并提供了对该实例的全局访问点。

用法示例

use WeDevs\WpUtils\SingletonTrait;

class MySingletonClass {

    use SingletonTrait;

    // Rest of your singleton class implementation...
}

// Get the instance of the singleton class
$instance = MySingletonClass::instance();

// Use the instance
$instance->doSomething();

许可证

此项目受GPL 2.0或更高版本的许可。