Створення свого контролера (поля)
Customizer дозволяє легко створювати власні поля (UI елементи). Давайте створимо підтримку поля type="range"(діапазон, повзунок, range slider). Таке поле дозволяє вибирати значення перетягуванням повзунка.
Контролери з ядра:
Базові поля:
color– WP_Customize_Color_Controldate_time– WP_Customize_Date_Time_Controltheme– WP_Customize_Theme_Control
Базові поля:
text,checkbox,textarea,radio,select,dropdown-pages, іemail,url,number,hidden,dateпрацюють через основний клас WP_Customize_Control::render_content() .
Nav Menu:
new_menu– WP_Customize_New_Menu_Controlnav_menu_name– WP_Customize_Nav_Menu_Name_Controlnav_menu_location– WP_Customize_Nav_Menu_Location_Controlnav_menu_item– WP_Customize_Nav_Menu_Item_Controlnav_menu_locations– WP_Customize_Nav_Menu_Locations_Controlnav_menu_auto_add– WP_Customize_Nav_Menu_Auto_Add_Control
Widget:
widget_form– WP_Widget_Form_Customize_Controlsidebar_widgets– WP_Widget_Area_Customize_Control
Image:
media– WP_Customize_Media_Controlimage– WP_Customize_Image_Controlbackground– WP_Customize_Background_Image_Controlcropped_image– WP_Customize_Cropped_Image_Controlheader– WP_Customize_Header_Image_Controlupload– WP_Customize_Upload_Control
Інші:
background_position– WP_Customize_Background_Position_Controlcode_editor– WP_Customize_Code_Editor_Control
Для створення нового поля потрібно створити клас на основі WP_Customize_Control :
<?php
if( class_exists( 'WP_Customize_Control' ) ) {
class WP_Customize_Range extends WP_Customize_Control {
public $type = 'range';
public function __construct( $manager, $id, $args = array() ) {
parent::__construct( $manager, $id, $args );
$defaults = [
'min' => 0,
'max' => 10,
'step' => 1
];
$ args = wp_parse_args ($ args, $ defaults);
$this->min = $args['min'];
$this->max = $args['max'];
$this->step = $args['step'];
}
public function render_content(){
?>
<label>
<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
<input class="range-slider"
min="<?php echo $this->min ?>"
max="<?php echo $this->max ?>"
step="<?php echo $this->step ?>"
type="range"
<?php $this->link(); ?>
value="<?php echo esc_attr( $this->value() ); ?>"
oninput="jQuery(this).next('input').val( jQuery(this).val() )">
<input type="text" value="<?php echo esc_attr( $this->value() ); ?>" onKeyUp="jQuery(this).prev('input').val( jQuery(this). val() )">
</label>
<?php
}
}
}Розширюємо базовий клас WP_Customize_Control . Оголошуємо в ньому властивість $typeта метод render_content(). У методі потрібно вивести HTML-елемент (поле форми), в якому потрібно використовувати методи:
- $this->value() – поточне значення поля.
- $this->link() – атрибут name поля.
min, max, step— це довільно створені властивості, які можна використовувати у класі.
Використання
Тепер приклад того, як використовувати наш новий контролер для створення нового поля.
add_action( 'customize_register', 'my_customize_register');
function my_customize_register( WP_Customize_Manager $wp_customize ){
$section = 'section_id';
$wp_customize->add_section( $section, [
'title' => 'My Settings',
'priority' => 220, // at the bottom of customizer
//'panel' => $panel,
]);
$wp_customize->add_setting( 'my_range' , array(
'default' => 0,
'transport' => 'postMessage',
)));
$wp_customize->add_control( new WP_Customize_Range( $wp_customize, 'my_range', [
'label' => 'Мій Рендж',
'min' => 10,
'max' => 9999,
'step' => 10,
'section' => 'section_id',
])));
}Зверніть увагу, що секція ‘section_id’ має бути створена. Як це робити дивіться тут .
Живий перегляд
Все, що потрібно зробити для підтримки live preview, це оновити поле в HTML новим значенням JavaScript.
wp.customize( 'my_range', function( value ) {
value.bind( function( newval ) {
$('#my_range span').html(newval);
} );
} );У результаті в нас вийде щось подібне:
