underpin/option-loader

Underpin 选项加载器

1.1.0 2021-11-23 14:21 UTC

This package is auto-updated.

Last update: 2024-09-23 22:41:35 UTC


README

一个帮助设置、保存和删除WordPress网站选项的加载器。

安装

使用Composer

composer require underpin/option-loader

手动安装

此插件使用内置的自动加载器,因此只要它在Underpin之前被要求,它就应该按预期工作。

require_once(__DIR__ . '/underpin-options/options.php');

设置

  1. 安装Underpin。请参阅Underpin 文档
  2. 根据需要注册新的选项菜单。

示例

一个非常基本的示例可能看起来像这样。

// Register option
underpin()->options()->add( 'example-option', [
	'key'           => 'example-option', // required
	'default_value' => 'optional default option value',
	'name'          => 'Human-readable name',
	'description'   => 'Human-readable description',
] );

或者,您可以扩展Option并直接引用扩展后的类,如下所示

underpin()->options()->add('option-key','Namespace\To\Class');

访问选项

基本示例

// Fetch from global context
underpin()->options()->get( 'example-option')->get();

当对象直接可访问时访问

// Fetch, given a meta factory
$meta = underpin()->options()->get('example-meta-field');

$meta->get( $object_id );

获取所有已注册的选项

// Fetch all registered options

// Typecasting options gets array of registered options objects.
$registered_options = (array) underpin()->options();
$values             = [];

foreach ( $registered_options as $key => $object ) {
	$values[ $key ] = $object->get();
}

重置所有已注册的选项

// Reset all options
$registered_options = (array) underpin()->options();

foreach($registered_user_meta as $object){
  $object->reset();    
}

从一个存储为数组的选项中提取选项值

在WordPress中,通常会将选项存储为序列化的数组,而不是创建多个数据库记录。因此,Underpin内置了一个帮助方法来从数据库中存储的选项数组中获取单个值。此方法使快速获取选项值成为可能。

给定此选项,其中存储的值是数组

underpin()->options()->add( 'example-option', [
	'key'           => 'example-option', // required
	'default_value' => [ 'item' => 'name', 'another_item' => 'another_value' ],
	'name'          => 'Human-readable name',
	'description'   => 'Human-readable description',
] );

您可以这样做,并获取单个值

underpin()->options()->pluck( 'example-option', 'another_item' ); // 'another_value'
underpin()->options()->pluck( 'example-option', 'invalid' ); // WP_Error