manzoorwanijk/cmb2-select-plus

CMB2 的改进选择字段

v1.0.1 2023-08-17 10:29 UTC

This package is auto-updated.

Last update: 2024-09-17 12:49:41 UTC


README

描述

select_plus 字段类型为 CMB2

此插件为 CMB2 添加了一个额外的字段类型:select_plus

该字段的功能与默认的 select 字段相似。然而,它增加了对 optgroup 和具有 multiple 属性的值保存的支持。

安装

您可以像安装 WordPress 插件一样安装此字段类型

  1. 下载插件
  2. 将插件文件夹放置在您的 /wp-content/plugins/ 目录中
  3. 在插件仪表板中激活插件

或者,您也可以在您的插件/主题中包含此字段类型。

您还可以使用 composer 安装此字段类型

composer require manzoorwanijk/cmb2-select-plus

用法

常规选择字段

// Select Field without optgroup
$cmb->add_field( array(
	'name'		=> 'Normal Select',
	'id'		=> $prefix . 'normal_select',
	'type'		=> 'select_plus',
	'options'	=> array(
		'standard' => 'Option One',
		'custom'   => 'Option Two',
		'none'     => 'Option Three',
	),
) );

Image

带有 optgroup 的选择字段

$cmb->add_field( array(
	'name'		=> 'Select+',
	'desc'		=> 'field description (optional)',
	'id'		=> $prefix . 'smart_select',
	'type'		=> 'select_plus',
	'options'	=> array(
		'Basic'	=> array( // optgroup
			1	=> 'Option One',
			2	=> 'Option Two',
			3	=> 'Option Three',
		),
		'Advanced'	=> array( // optgroup
			4	=> 'Option Four',
			5	=> 'Option Five',
			6	=> 'Option Six',
		),
	),
) );

Image

multiple 属性

您可以使用 multiple 属性,字段值将作为数组保存

// Select Field without optgroup and with multiple attribute
$cmb->add_field( array(
	'name'		=> 'Normal Select',
	'id'		=> $prefix . 'normal_select_multi',
	'type'		=> 'select_plus',
	'options'	=> array(
		'standard' => 'Option One',
		'custom'   => 'Option Two',
		'none'     => 'Option Three',
	),
	'attributes'	=> array(
		'multiple'	=> 'multiple',
	),
) );
// Select Field with optgroup and multiple attribute
$cmb->add_field( array(
	'name'		=> 'Select+',
	'desc'		=> 'field description (optional)',
	'id'		=> $prefix . 'smart_select_multi',
	'type'		=> 'select_plus',
	'options'	=> array(
		'Basic'	=> array( // optgroup
			1	=> 'Option One',
			2	=> 'Option Two',
			3	=> 'Option Three',
		),
		'Advanced'	=> array( // optgroup
			4	=> 'Option Four',
			5	=> 'Option Five',
			6	=> 'Option Six',
		),
	),
	'attributes'	=> array(
		'multiple'	=> 'multiple',
	),
) );

为什么是 Select_Plus_CMB2_Types 类?

  • 这使您可以在只需要渲染字段而不是整个行的情况下灵活使用。
  • 它允许您覆盖字段的默认参数
// field args
$args = array(
    'field_args'    => array(
        'id'        => 'some_id_here',
        'type'      => 'select_plus',
        'options'   => array(
            'standard' => 'Option One',
            'custom'   => 'Option Two',
            'none'     => 'Option Three',
        ),
) );
// create field
$field = new CMB2_Field( $args );

// pass the field to custom class
$types = new Select_Plus_CMB2_Types( $field );

// render the field with new id and name
echo $types->select_plus( array(
    'id'    => 'new_id_0_here',
    'name'  => 'smart[param][value]',
) );