• CSS
    • ПРОГРАММИРОВАНИЕ (CODING)
    • Emmet, ul, li, table, form
    • Style, hover, child
    • CSS Hat, font, background
    • Reset, margin, padding, float
    • Base64, relative, z-index
    • Google Fonts, PSD
    • Brackets, Bootstrap
    • Script, src, comments
    • jQuery, Slick Js, Tooltip
    • Bootstrap, Slick Nav, @media
    • Mobile Vew, Font Awesome
    • SASS, Bootstrap
    • Flexbox, Slider
  • Word Press
    • #1. Introduction to WordPress
    • #2. WordPress Files Configuration
    • #3. Kernel Review. Codex
    • #4. Standards of Encoding
    • #5. Develop a plugin, introduction
    • #6. Hooks, Filters, InterNation
    • #7. Adding Admin Menus, JS, CSS
    • #8. HTTP API, Shortcodes, Transients
    • #9. Options API, Settings API
    • #10. Database API, $wpdb object
    • #11. Ajax. Widget API. Dashboard API
    • #12. Post Type. Taxonomies. Metadata
    • #13. Theme Development. Basics
    • #14. Loop. Template. WP_Query
    • #15. File functions.php – I
    • #16. File functions.php – II
    • #17. Child Theme. Shortcode. TinyMCE
    • #18. Frameworks. Blank Theme
    • #19. Framework. Underscores. Unyson
    • #20: Framework Unyson. Options
    • #21. Extensions, Components, Manifest
    • #22. Unyson: Built-in Extensions
    • #23. Unyson: Helpers, Filters & Actions
    • #24. WC: Installation & Updating
    • #25. WC: Settings & Options
    • #26. WC: Product Setup
    • #27. WC: Sell Products, Order
    • #28. WC: Theming
    • #29. WC: Extending
    • #30. WC: Extending
  • PHP
    • Laravel, MVC, Composer
    • FW Yii2
  • JS
    • JS
    • React, Angular
  • Freelance
  • Projects
    • Useful Products
      • Free WordPress Themes (WP)
      • Free CSS templates (CSS, HTML)
      • Стартовая тема Word Press (WP)
    • Project
      • Practic Task
      • Real Democracy Game
      • Research Journal
      • Qubot
      • Cyber-street
      • Amatue

#20: Framework Unyson. Options

Rostyslav - 24 января, 2018 - Comments off

    Options (параметры)

    Options files

    Containers

    Ограничения

    Theme Integration

    Customizer Options

    Settings Options

    Post Options

    Customizer

    Примеры

    Дополнительные аргументы

    Live Preview

    Option Types

    Built-in Option Types

    Create Option Type

    Custom Save Location

    Options

    Unyson Options

    Options предназначены для создания полей формы, представляющих различные типы данных, например. Rich и plain text, icons, мультимедийный контент, шрифты и многое другое. С помощью option вы можете легко создавать вкладки, поля и формы для страниц администратора. Вы просто создаете массив, и он будет преобразован в html. При отправке формы значения будут сохранены в базе данных, и вы сможете обращаться к ним в любом месте, где хотите, с помощью вспомогательных функций опции fw_get_db _…_ option ().

    Для продвинутых пользователей это простой способ создания входов форм и их использования для различных целей. Простейший массив параметров выглядит примерно так:

    $options = array(

       ‘option_id’ => array(

           ‘type’ => ‘text’ ) );

    Это создаст text input. Ключ массива используется как идентификатор опции, он должен быть уникальным. Значения в базе данных будут храниться в виде массива (‘option_id’ => ‘value’).

    Единственным обязательным параметром для любого параметра является type.

    Все Options имеют некоторые базовые параметры:

    • label (string) Label
    • desc (string) Description
    • value (mixed) Default value
    • attr (array) HTML attributes
    • help (string|array) Дополнительная информация об опции. Это создаст подсказку рядом с опцией, которая покажет текст в всплывающей подсказке.

    Некоторые параметры могут иметь дополнительные (необязательные) параметры.

    $options = array(

       ‘option_id’ => array(

           ‘type’  => ‘text’,

           ‘value’ => ‘Default value’,

           ‘label’ => __(‘Option Label’, ‘{domain}’),

           ‘desc’  => __(‘Option Description’, ‘{domain}’),

           ‘attr’  => array(‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’),

           ‘help’  => __(‘Some html that will appear in tip popup’, ‘{domain}’), ) );

    Options files

    Это основные места, где используются опции:

    • Theme Settings Page: Загружает options из

    {theme}/framework-customizations/theme/options/settings.php

    • Customizer Page: Загружает options из {theme}/framework-customizations/theme/options/customizer.php
    • Post Add/Edit Page: Загружает options из {theme}/framework-customizations/theme/options/posts/{$post_type}.php
    • Taxonomy Term Edit Page: Загружает options из  {theme}/framework-customizations/theme/options/taxonomies/{$taxonomy}.php

    Containers

    Options, которые не имеют значения и содержат другие options в параметре options, являются контейнерами. Если options имеет  options параметр, он считается контейнером.

    Самый простой массив опций контейнера выглядит так, как показано в следующем примере, и будет генерировать пустой метаблок без заголовка:

    $options = array(

       array(

           ‘type’    => ‘box’,

           ‘options’ => array() ) );

    Существует 4 встроенных типа контейнера:

    box — WordPress metabox

    ‘box_id’ => array(

       ‘type’ => ‘box’,

       ‘options’ => array(

           ‘option_id’  => array( ‘type’ => ‘text’ ),  ),

       ‘title’ => __(‘Box Title’, ‘{domain}’),

       ‘attr’ => array(‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’),

       /**

        * When used in Post Options on the first array level

        * the «box« container accepts additional parameters

        */

       //’context’ => ‘normal|advanced|side’,

       //’priority’ => ‘default|high|core|low’, ),

    tab — Одна вкладка (вкладки с одного и того же уровня массива будут собираться и отображаться в виде нескольких вкладок)

    ‘tab_id’ => array(

       ‘type’ => ‘tab’,

       ‘options’ => array(

           ‘option_id’  => array( ‘type’ => ‘text’ ), ),

       ‘title’ => __(‘Tab Title’, ‘{domain}’),

       ‘attr’ => array(‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’), ),

    ‘tab_id_2’ => array(

       ‘type’ => ‘tab’,

       ‘options’ => array(

           ‘option_id_2’  => array( ‘type’ => ‘text’ ),  ),

       ‘title’ => __(‘Tab Title #2’, ‘{domain}’),

       ‘attr’ => array(‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’), ),

    group — Группировка опций в оболочку div. Не имеет дизайна. Обычно используется для отображения / скрытия группы опций из javascript

    ‘group_id’ => array(

       ‘type’ => ‘group’,

       ‘options’ => array(

           ‘option_id’  => array( ‘type’ => ‘text’ ), ),

       ‘attr’ => array(‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’), ),

    popup — Кнопка, при нажатии на нее открывается модальный вариант с опциями

    ‘popup_id’ => array(

       ‘type’ => ‘popup’,

       ‘options’ => array(

           ‘option_id’  => array( ‘type’ => ‘text’ ), ),

       ‘title’ => __(‘Button and Popup Title’, ‘{domain}’),

       ‘attr’ => array(‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’),

       ‘modal-size’ => ‘small’, // small, medium, large

       ‘desc’ => __(‘Button Description’, ‘{domain}’), ),

    Ограничения

    Параметр attr из Post Options первого уровня не используется. Поскольку box добавляются с помощью add_meta_box(), у которого нет параметра для указания атрибутов.

    Theme Integration

    С помощью опций вы можете легко создавать формы администратора и использовать значения во внешнем интерфейсе.

    Customizer Options

    Создайте {theme} /framework-customizations/theme/options/customizer.php со следующим содержимым:

    <?php if (!defined( ‘FW’ )) die(‘Forbidden’);

    $options = array(

       ‘body-color’ => array(

           ‘type’ => ‘color-picker’,

           ‘label’ => __(‘Body Color’, ‘{domain}’),

           ‘value’ => ‘#ADFF2F’, ), );

    Добавить в {theme} /functions.php

    function _action_theme_wp_print_styles() {

       if (!defined(‘FW’)) return; // prevent fatal error when the framework is not active

       $option_value = fw_get_db_customizer_option(‘body-color’);

       echo ‘<style type=»text/css»>’

            . ‘body { ‘

            . ‘border: 30px solid ‘. esc_html($option_value) .’; ‘

            . ‘}’

            . ‘</style>’; }

    add_action(‘wp_print_styles’, ‘_action_theme_wp_print_styles’);

    Перейти к меню Appearance > Customize, найти опцию  Body Color и изменить его.

    Settings Options

    Создайте {theme} /framework-customizations/theme/options/settings.php со следующим содержимым:

    <?php if (!defined( ‘FW’ )) die(‘Forbidden’);

    $options = array(

       ‘body-color’ => array(

           ‘type’ => ‘color-picker’,

           ‘label’ => __(‘Body Color’, ‘{domain}’),

           ‘value’ => ‘#ADFF2F’,  ), );

    Добавить в {theme} /functions.php

    function _action_theme_wp_print_styles() {

       if (!defined(‘FW’)) return; // prevent fatal error when the framework is not active

       $option_value = fw_get_db_settings_option(‘body-color’);

       echo ‘<style type=»text/css»>’

            . ‘body { ‘

            . ‘border: 30px solid ‘. esc_html($option_value) .’; ‘

            . ‘}’

            . ‘</style>’; }

    add_action(‘wp_print_styles’, ‘_action_theme_wp_print_styles’);

    Перейти к меню Appearance > Customize, найти опцию  Body Color и изменить его.

    Post Options

    Создайте {theme} /framework-customizations/theme/options/posts/post.php со следующим содержимым:

    <?php if (!defined( ‘FW’ )) die(‘Forbidden’);

    $options = array(

       ‘main’ => array(

           ‘type’ => ‘box’,

           ‘title’ => __(‘Testing Options’, ‘{domain}’),

           ‘options’ => array(

               ‘body-color’ => array(

                   ‘type’ => ‘color-picker’,

                   ‘label’ => __(‘Body Color’, ‘{domain}’),

                   ‘value’ => ‘#ADFF2F’,   ),   ),   ), );

    Добавить в {theme} /functions.php

    function _action_theme_wp_print_styles() {

       if (!defined(‘FW’)) return; // prevent fatal error when the framework is not active

       global $post;

       if (!$post || $post->post_type != ‘post’) {

           return; }

       $option_value = fw_get_db_post_option($post->ID, ‘body-color’);

       echo ‘<style type=»text/css»>’

            . ‘body { ‘

            . ‘border: 30px solid ‘. esc_html($option_value) .’; ‘

            . ‘}’

            . ‘</style>’; }

    add_action(‘wp_print_styles’, ‘_action_theme_wp_print_styles’);

    Customizer

    Customizer Options {theme}/framework-customizations/theme/options/customizer.php превращаются в элементы Customizer (panels, sections и controls).

    Элементы кастомизации имеют строгую структуру, которая также применяется к структуре массива options:

      • Контейнеры могут быть вложены только в 2 уровня
        • container > option превращается в section > control

     

    • container > container > option превращается в panel > section > control
    • container > container > container > option не будет работать panel > section > ERROR

     

    • Контейнеры должны содержать только options или только контейнеры, потому что панель не может содержать как sections, так и элементы controls.

    Примеры

    {theme}/framework-customizations/theme/options/customizer.php

    Создать Section

    $options = array(

       ‘section_1’ => array(

           ‘title’ => __(‘Unyson Section’, ‘{domain}’),

           ‘options’ => array(

               ‘option_1’ => array(

                   ‘type’ => ‘text’,

                   ‘value’ => ‘Default Value’,

                   ‘label’ => __(‘Unyson Option’, ‘{domain}’),

                   ‘desc’ => __(‘Option Description’, ‘{domain}’), ), ), ), );

    Создание Panel с Sections

    $options = array(

       ‘panel_1’ => array(

           ‘title’ => __(‘Unyson Panel’, ‘{domain}’),

           ‘options’ => array(

               ‘section_1’ => array(

                   ‘title’ => __(‘Unyson Section #1’, ‘{domain}’),

                   ‘options’ => array(

                       ‘option_1’ => array(

                           ‘type’ => ‘text’,

                           ‘value’ => ‘Default Value’,

                           ‘label’ => __(‘Unyson Option #1’, ‘{domain}’),

                           ‘desc’ => __(‘Option Description’, ‘{domain}’),  ), ), ),

               ‘section_2’ => array(

                   ‘title’ => __(‘Unyson Section #2’, ‘{domain}’),

                   ‘options’ => array(

                       ‘option_2’ => array(

                           ‘type’ => ‘text’,

                           ‘value’ => ‘Default Value’,

                           ‘label’ => __(‘Unyson Option #2’, ‘{domain}’),

                           ‘desc’ => __(‘Option Description’, ‘{domain}’), ),

                       ‘option_3’ => array(

                           ‘type’ => ‘text’,

                           ‘value’ => ‘Default Value’,

                           ‘label’ => __(‘Unyson Option #3’, ‘{domain}’),

                           ‘desc’ => __(‘Option Description’, ‘{domain}’), ), ), ), ), ), );

    Получить option database/сохраненное значение в шаблоне

    $value = fw_get_db_customizer_option(‘option_1’);

    Дополнительные аргументы

    Аргументы управления могут быть установлены в параметре опции wp-customizer-args.

    $options = array(

       ‘section_1’ => array(

           ‘title’ => __(‘Unyson Section’, ‘{domain}’),

           ‘options’ => array(

               ‘option_1’ => array(

                   ‘type’ => ‘text’,

                   ‘value’ => ‘Default Value’,

                   ‘label’ => __(‘Unyson Option’, ‘{domain}’),

                   ‘desc’ => __(‘Option Description’, ‘{domain}’),

                   ‘wp-customizer-args’ => array(

                       ‘priority’ => 3, ), ), ), ), );

    Параметры настройки могут быть установлены в параметре опции wp-customizer-setting-args.

    $options = array(

       ‘section_1’ => array(

           ‘title’ => __(‘Unyson Section’, ‘{domain}’),

           ‘options’ => array(

               ‘option_1’ => array(

                   ‘type’ => ‘text’,

                   ‘value’ => ‘Default Value’,

                   ‘label’ => __(‘Unyson Option’, ‘{domain}’),

                   ‘desc’ => __(‘Option Description’, ‘{domain}’),

                   ‘wp-customizer-setting-args’ => array(

                       ‘capability’ => ‘edit_posts’, ), ), ), ), );

    Live Preview

    В фоновом режиме customizer options преобразуются в элементы customizer, поэтому они следуют по умолчанию WordPress и реализуют предварительный просмотр в реальном времени, используя стандартное решение WordPress.

    Измените настройку transport и добавьте в очередь javascript

    // file: {theme}/inc/hooks.php

    if (defined(‘FW’)):

       /**

        * @param WP_Customize_Manager $wp_customize

        * @internal

        */

       function _action_customizer_live_fw_options($wp_customize) {

           if ($wp_customize->get_setting(‘fw_options[OPTION_ID]’)) {

               $wp_customize->get_setting(‘fw_options[OPTION_ID]’)->transport = ‘postMessage’;

               add_action( ‘customize_preview_init’, ‘_action_customizer_live_fw_options_preview’ ); }  }

       add_action(‘customize_register’, ‘_action_customizer_live_fw_options’);

       /**

        * @internal

        */

       function _action_customizer_live_fw_options_preview() {

           wp_enqueue_script(

               ‘mytheme-customizer’,

               get_template_directory_uri() .’/assets/js/theme-customizer.js’,

               array( ‘jquery’,’customize-preview’ ),

               fw()->theme->manifest->get_version(),

               true ); }

    endif;

    Обрабатывать изменения в javascript

    // file: {theme}/assets/js/theme-customizer.js

    ( function( $ ) {

       wp.customize( ‘fw_options[OPTION_ID]’, function( value ) {

           value.bind( function( newval ) {

               /**

                * An array of collected html inputs

                * [{‘name’:’input[name]’,’value’:’input value’}]

                * or

                * [{‘name’:’input[name]’,’value’:’input value’},{‘name’:’input[name]’,’value’:’input value’},…]

                */

               newval = JSON.parse(newval);

               $( ‘h1’ ).text( newval[0].value );  } );  } );

    } )( jQuery );

    Значение находится в формате [{‘name’: ‘input [name]’, ‘value’: ‘input value’}], потому что форма customizer не представлена в виде обычной формы. Элемент control может хранить свое значение только внутри одного входа, который имеет некоторые специальные атрибуты (вместо name = «…»), и он отслеживается для изменений сценарием Customizer, чтобы инициировать предварительное обновление. Из-за этого параметры структуры собирают все свои значения входов и сохраняют их в этом специальном входе (здесь приведено расширенное объяснение).

    Option Types

    Каждый option имеет type в качестве обязательного параметра. Его значением должен быть существующий зарегистрированный тип параметра.

    HTML

    Все option types должны иметь класс .fw-option-type- {type} в main/wrapper html-элемента.

    CSS

    Если в option type есть css, все правила должны начинаться с префикса .fw-option-type- {type} class:

    /* correct */

    .fw-option-type-demo .some-class {

       color: blue; }

    /* wrong */

    .some-class {

       color: blue; }

    Это делается для предотвращения конфликтов CSS.

    Javascript

    Все javascript должны придерживаться класса .fw-option-type- {type} и работать только внутри элемента main / wrapper (никаких событий, связанных с телом). Если в option type есть пользовательские события javascript, эти события должны быть активированы в главном элементе.

    $someInnerElement.closest(‘.fw-option-type-demo’)

       .trigger(‘fw:option-type:demo:custom-event’, {some: ‘data’});

    Если в документации указано, что в option type имеются пользовательские события, это означает, что вы можете присоединить прослушиватели событий к элементам с классом .fw-option-type- {type} (а не к телу или fwEvents).

    ПРЕДОСТЕРЕЖЕНИЕ

    Не путайте .fw-option-type- {type} с классом .fw-backend-option-type- {type}, который используется внутри framework и не должен использоваться в scripts option type.

    Built-in Option Types

    Built-in Option Types

    Вот полный список всех встроенных типов опций со всеми доступными параметрами для каждого параметра.

    Text

    Регулярный text input.

    array(

       ‘type’  => ‘text’,

       ‘value’ => ‘default value’,

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’), )

    Textarea

    Регулярный textarea.

    array(

       ‘type’  => ‘textarea’,

       ‘value’ => ‘default value’,

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’), )

    Checkbox

    Single checkbox.

    array(

       ‘type’  => ‘checkbox’,

       ‘value’ => true, // checked/unchecked

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

       ‘text’  => __(‘Yes’, ‘{domain}’), )

    Checkboxes

    Список checkboxes.

    array(

       ‘type’  => ‘checkboxes’,

       ‘value’ => array(

           ‘choice-1’ => false,

           ‘choice-2’ => true, ),

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

       ‘choices’ => array( // Примечание: избегайте использования ключей bool или int http://bit.ly/1cQgVzk

           ‘choice-1’ => __(‘Choice 1’, ‘{domain}’),

           ‘choice-2’ => __(‘Choice 2’, ‘{domain}’),

           ‘choice-3’ => __(‘Choice 3’, ‘{domain}’), ),

       // Display choices inline instead of list

       ‘inline’ => false, )

    Radio

    Список radio buttons.

    array(

       ‘type’  => ‘radio’,

       ‘value’ => ‘choice-3’,

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

       ‘choices’ => array( // Note: Avoid bool or int keys http://bit.ly/1cQgVzk

           ‘choice-1’ => __(‘Choice 1’, ‘{domain}’),

           ‘choice-2’ => __(‘Choice 2’, ‘{domain}’),

           ‘choice-3’ => __(‘Choice 3’, ‘{domain}’), ),

       // Display choices inline instead of list

       ‘inline’ => false, )

    Select

    Регулярный select.

    array(

       ‘type’  => ‘select’,

       ‘value’ => ‘choice-3’,

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

       ‘choices’ => array(

           » => ‘—‘,

           ‘choice-1’ => __(‘Choice 1’, ‘{domain}’),

           ‘choice-2’ => array(

               ‘text’ => __(‘Choice 2’, ‘{domain}’),

               ‘attr’ => array(‘data-foo’ => ‘bar’), ),

           array( // optgroup

               ‘attr’    => array(‘label’ => __(‘Group 1’, ‘{domain}’)),

               ‘choices’ => array(

                   ‘choice-3’ => __(‘Choice 3’, ‘{domain}’),

                   // …

               ), ), ),

       /**

        * Разрешить сохранение не существующих вариантов

    Полезно, когда вы используете select для его динамического заполнения из js

        */

       ‘no-validate’ => false, )

    Select Multiple

    Select с несколькими значениями.

    array(

       ‘type’  => ‘select-multiple’,

       ‘value’ => array( ‘choice-1’, ‘choice-3’ ),

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

       ‘choices’ => array(

           » => ‘—‘,

           ‘choice-1’ => __(‘Choice 1’, ‘{domain}’),

           ‘choice-2’ => array(

               ‘text’ => __(‘Choice 2’, ‘{domain}’),

               ‘attr’ => array(‘data-foo’ => ‘bar’), ),

           array( // optgroup

               ‘attr’    => array(‘label’ => __(‘Group 1’, ‘{domain}’)),

               ‘choices’ => array(

                   ‘choice-3’ => __(‘Choice 3’, ‘{domain}’),

                   // …

               ), ), ), )

    Multi-Select

    Select несколько вариантов из разных источников: posts, taxonomies, users или custom array.

    array(

           ‘type’  => ‘multi-select’,

           ‘value’ => array( ‘choice-1’, ‘choice-3’ ),

           ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

           ‘label’ => __(‘Label’, ‘{domain}’),

           ‘desc’  => __(‘Description’, ‘{domain}’),

           ‘help’  => __(‘Help tip’, ‘{domain}’),

           /**

            * Set population method

            * Доступны: ‘posts’, ‘taxonomy’, ‘users’, ‘array’

            */

           ‘population’ => ‘array’,

           /**

            * Установить post types, taxonomies, user roles для поиска

            *

            * ‘population’ => ‘posts’

            * ‘source’ => ‘page’,

            *

            * ‘population’ => ‘taxonomy’

            * ‘source’ => ‘category’,

            *

            * ‘population’ => ‘users’

            * ‘source’ => array( ‘editor’, ‘subscriber’, ‘author’ ),

            *

            * ‘population’ => ‘array’

            * ‘source’ => » // will populate with ‘choices’ array

            */

           ‘source’ => »,

           //’population’ => ‘posts’,

           //’source’ => ‘post’,

           /**

            * Установите количество posts/users/taxonomies, которые будут выбраны с множественным выбором

            * Или установите значение false, чтобы отключить эту функцию.

            */

           ‘prepopulate’ => 10,

           /**

            * Массив с доступными вариантами выбора

            * Используется только тогда, когда ‘population’ => ‘array’

            */

           ‘choices’ => array(

               ‘choice-1’ => __(‘Choice 1’, ‘{domain}’),

               ‘choice-2’ => __(‘Choice 2’, ‘{domain}’),

               ‘choice-3’ => __(‘Choice 3’, ‘{domain}’), ),

           /**

            * Установить количество максимальных элементов, которые могут быть выбраны

            */

           ‘limit’ => 100, ),

    Switch

    Switch между двумя вариантами.

    array(

       ‘type’  => ‘switch’,

       ‘value’ => ‘hello’,

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

       ‘left-choice’ => array(

           ‘value’ => ‘goodbye’,

           ‘label’ => __(‘Goodbye’, ‘{domain}’), ),

       ‘right-choice’ => array(

           ‘value’ => ‘hello’,

           ‘label’ => __(‘Hello’, ‘{domain}’), ), )

    Пользовательские события

    fw:option-type:switch:change — Значение было изменено.

    Значение переключателя в html закодировано json для предотвращения проблем с булевыми значениями, поэтому перед использованием значения html в javascript do value = JSON.parse (value);

    Color Picker

    Выбери цвет.

    array(

       ‘type’  => ‘color-picker’,

       ‘value’ => ‘#FF0000’,

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       // palette colors array

       ‘palettes’ => array( ‘#ba4e4e’, ‘#0ce9ed’, ‘#941940’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

    )

    RGBA Color Picker

    Выберите цвет rgba().

    array(

       ‘type’  => ‘rgba-color-picker’,

       ‘value’ => ‘rgba(255,0,0,0.5)’,

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       // palette colors array

       ‘palettes’ => array( ‘#ba4e4e’, ‘#0ce9ed’, ‘#941940’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

    )

    Gradient

    Выберите цвета градиента.

    array(

       ‘type’  => ‘gradient’,

           ‘value’ => array(

               ‘primary’   => ‘#FF0000’,

               ‘secondary’ => ‘#0000FF’,  ),

           ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

           ‘label’ => __(‘Label’, ‘{domain}’),

           ‘desc’  => __(‘Description’, ‘{domain}’),

           ‘help’  => __(‘Help tip’, ‘{domain}’), )

    Image Picker

    Выберите изображение.

    array(

      ‘type’  => ‘image-picker’,

           ‘value’ => ‘value-3’,

           ‘attr’  => array(

               ‘class’    => ‘custom-class’,

               ‘data-foo’ => ‘bar’, ),

           ‘label’ => __(‘Label’, ‘{domain}’),

           ‘desc’  => __(‘Description’, ‘{domain}’),

           ‘help’  => __(‘Help tip’, ‘{domain}’),

           ‘choices’ => array(

               ‘value-1′ => get_template_directory_uri() .’/images/thumbnail.png’,

               ‘value-2’ => array(

                   // (required) url for thumbnail

                   ‘small’ => get_template_directory_uri() .’/images/thumbnail.png’,

                   // (optional) url  для большого изображения, которое появится в подсказке

                   ‘large’ => get_template_directory_uri() .’/images/preview.png’,

                   // (optional) Выбор дополнительных данных для js, доступных в пользовательских событиях

                   ‘data’ => array()  ),

               ‘value-3’ => array(

                   // (required) url for thumbnail

                   ‘small’ => array(

                       ‘src’ => get_template_directory_uri() .’/images/thumbnail.png’,

                       ‘height’ => 70  ),

                   // (optional) url for large image that will appear in tooltip

                   ‘large’ => array(

                       ‘src’ => get_template_directory_uri() .’/images/preview.png’,

                       ‘height’ => 400  ),

                   // (optional) choice extra data for js, available in custom events

                   ‘data’ => array()  ), ),

           ‘blank’ => true, // (optional) Если true, изображения могут быть отменены )

    Custom Events

    fw:option-type:image-picker:clicked — Был нажат thumbnail.

    fw:option-type:image-picker:changed — Значение изменено

    Background Image

    Выберите фоновое изображение.

    array(

       ‘type’  => ‘background-image’,

       ‘value’ => ‘bg-1’,

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

       ‘choices’ => array(

           ‘none’ => array(

               ‘icon’ => get_template_directory_uri() . ‘/images/bg/bg-0.jpg’,

               ‘css’  => array(

                   ‘background-image’ => ‘none’ ), ),

           ‘bg-1’ => array(

               ‘icon’  => get_template_directory_uri() . ‘/images/bg/bg-1.jpg’,

               ‘css’  => array(

                   ‘background-image’  => ‘url(«‘ . get_template_directory_uri() . ‘/images/bg-1.png’ . ‘»)’,

                   ‘background-repeat’ => ‘repeat’, ), ),

           ‘bg-2’ => array(

               ‘icon’ => get_template_directory_uri() . ‘/images/bg/bg-2.jpg’,

               ‘css’  => array(

                   ‘background-image’  => ‘url(«‘ . get_template_directory_uri() . ‘/images/bg-2.png’ . ‘»)’,

                   ‘background-repeat’ => ‘repeat-y’ ), ) ) )

    Date Picker

    Выберите дату в календаре.

    array(

       ‘type’  => ‘date-picker’,

           ‘value’ => »,

           ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

           ‘label’ => __(‘Label’, ‘{domain}’),

           ‘desc’  => __(‘Description’, ‘{domain}’),

           ‘help’  => __(‘Help tip’, ‘{domain}’),

           ‘monday-first’ => true, // Неделя начнется с понедельника; Для воскресенья установлено значение false

           ‘min-date’ => date(‘d-m-Y’), // По умолчанию минимальной датой будет текущий день. Установите дату в формате d-m-Y в качестве даты начала

           ‘max-date’ => null, // По умолчанию максимальная дата не указана. Установите дату в формате d-m-Y в качестве даты начала

    )

    Datetime Picker

    Выберите дату и время в календаре.

    array(

       ‘type’  => ‘datetime-picker’,

           ‘value’ => »,

           ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

           ‘label’ => __(‘Label’, ‘{domain}’),

           ‘desc’  => __(‘Description’, ‘{domain}’),

           ‘help’  => __(‘Help tip’, ‘{domain}’),

           ‘datetime-picker’ => array(

               ‘format’        => ‘Y/m/d H:i’, // Формат даты и времени

               ‘maxDate’       => false,  // По умолчанию defautFormat datetimelt нет максимальной даты, установите дату в формате даты и времени..

               ‘minDate’       => false,  // По умолчанию минимальная дата будет текущим днем, установите дату в формате даты и времени.

               ‘timepicker’    => true,   // Show timepicker.

               ‘datepicker’    => true,   // Show datepicker.

               ‘defaultTime’   => ’12:00′ // Если входное значение пустое, timepicker установит время использования defaultTime.

           ), )

    Datetime Range

    Установите диапазон дат.

    array(

       ‘type’  => ‘datetime-range’,

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

       ‘datetime-pickers’ => array(

       ‘from’ => array(

           ‘minDate’ => ‘1970/01/01’, // By default minimum date will be current day, set a date in the datetime format.

           ‘maxDate’ => ‘2038/01/19’, // By default there is not maximum date , set a date in the datetime format.

           ‘format’  => ‘Y/m/d H:i’,  // Format datetime.

           ‘timepicker’  => true,     // Show timepicker.

           ‘datepicker’  => true,     // Show datepicker.

           ),

       ‘to’ => array(

           ‘minDate’ => ‘1970/01/01’, // By default minimum date will be current day, set a date in the datetime format.

           ‘maxDate’ => ‘2038/01/19’, // By default there is not maximum date , set a date in the datetime format.

           ‘format’  => ‘Y/m/d H:i’,  // Format datetime.

           ‘timepicker’  => true,     // Show timepicker.

           ‘datepicker’  => true,     // Show datepicker.

           )  ),

       ‘value’ => array(

           ‘from’ => »,

           ‘to’ => »   ) )

    Icon v2

    array(

           ‘type’  => ‘icon-v2’,

           /**

            * small | medium | large | sauron

            * Yes, sauron. Definitely try it. Great one.

            */

           ‘preview_size’ => ‘medium’,

           /**

            * small | medium | large

            */

           ‘modal_size’ => ‘medium’,

           /**

            * Здесь нет смысла настраивать значение из кода.

            *

            * Я задокументирую результат, который вы получите в интерфейсе здесь::

            * ‘value’ => array(

            *   ‘type’ => ‘icon-font’, // icon-font | custom-upload

            *

            *   // ONLY IF icon-font

            *   ‘icon-class’ => »,

            *   ‘icon-class-without-root’ => false,

            *   ‘pack-name’ => false,

            *   ‘pack-css-uri’ => false

            *

            *   // ONLY IF custom-upload

            *   // ‘attachment-id’ => false,

            *   // ‘url’ => false

            * ),

            */

           ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

           ‘label’ => __(‘Label’, ‘{domain}’),

           ‘desc’  => __(‘Description’, ‘{domain}’),

           ‘help’  => __(‘Help tip’, ‘{domain}’), ),

    Значение по умолчанию на самом деле не поддерживается из-за сложности данных, которые хранятся в этом типе.

    Вторая версия первого Icon option type. Это было улучшено с точки зрения как пользовательского интерфейса, так и расширяемости. Пользователь сможет фильтровать список пакетов icon, а также загружать собственные icon. Значение результата будет содержать поле type и оно будет содержать тип выбранного содержимого. Это может быть icon-font или custom-upload. Вы также получите любимый icon functionallity, который будет работать из коробки.

    Вам нужно будет включить загрузку SVG самостоятельно, используя hook в вашей теме.

    По умолчанию у нас есть только 6 пакетов icon, которые включены и обслуживаются самим Unyson.

    • Font Awesome
    • Entypo
    • Linecons
    • Linearicons
    • Typicons
    • Unycons

    ЗАМЕТКА

    По умолчанию ни один из этих пакетов не будет помещен во frontend интерфейс вашей темы.

    Вы должны вызвать это, чтобы поставить их в очередь:

    fw()->backend->option_type(‘icon-v2’)->packs_loader->enqueue_frontend_css();

    Configure Icon Packs

    Icon V2 легко расширяется с помощью нескольких фильтров, которые вы можете подключить. Во-первых, вы можете настроить, какой из уже зарегистрированных пакетов мы должны отображать в подборщике.

    function _custom_packs_list($current_packs) {

       /**

        * $current_packs это массив имен пакетов.

        * Вы должны вернуть тот, который вы хотите показать в подборщике..

        */

       return array(‘font-awesome’, ‘unycon’);

    }

    add_filter(‘fw:option_type:icon-v2:filter_packs’, ‘_custom_packs_list’);

    ЗАМЕТКА

    Это глобальный hook, который изменяет поведение всех pickers. Настройка пакетов в picker недоступна и не будет реализована позже. Если у вас есть для этого конкретный пример использования, пожалуйста, заполните проблему.

    Add Icon Pack

    Короче говоря, вы можете добавить больше пакетов, фильтруя на fw:option_type:icon-v2:packs filter. Простейший пример: все ключи required:

    add_filter(‘fw:option_type:icon-v2:packs’, ‘_add_my_pack’);

    function _add_my_pack($default_packs) {

       /**

        * No fear. Defaults packs will be merged in back. You can’t remove them.

        * Changing some flags for them is allowed.

        */

       return array(

         ‘my_pack’ => array(

           ‘name’ => ‘my_pack’, // same as key

           ‘title’ => ‘My Cool Pack’,

           ‘css_class_prefix’ => ‘my-pack’,

           ‘css_file’ => ‘path_to_css_file’,

           ‘css_file_uri’ => ‘network_accessible_url’ ) ) }

    И это будет работать для большинства случаев. Вам не нужно указывать, какие icons должны отображаться внутри picker. Все они будут показаны, по умолчанию. На самом деле, есть какая-то магия, которая будет извлекать все ваши icons и отображать их. Я попытаюсь объяснить это ниже.

    Вычислительный список icons

    По умолчанию, когда вы регистрируетесь icons пакет эти icons будут извлечены из файла CSS автоматически, так что вы не должны поддерживать длинный массив иконок для каждого пакета. Вместо этого мы вместо этого делаем некоторые трюки. Мы изучаем css-файл для каждого пакета и ищем шаблоны, которые выглядят так:

    .`css_class_prefix`-some-icon:before {

       content: ‘\266a’;

    }

    css_class_prefix там ссылается на параметр css_class_prefix, указанный вами для вашего пакета icon.

    // Those will be considered an icon

    .my-pack-some-icon:before { content: ‘\266a’; }

    .my-pack.my-pack-some-icon:before { content: ‘\266a’; }

    .my-pack.my-pack-some-icon:after { content: ‘\266a’; }

    // This one won’t

    .my-pack.my-pack-some-icon:after { color: red; }

    Вообще говоря, это то, что пакет CSS icon состоит из:

    • @font-face Правила
    • icon generations – мы стараемся, чтобы получить только их
    • Некоторые другие помощники общего назначения — они встречаются не так часто

    Вы также можете полностью остановить этот механизм для одного пакета, указав массив значков для iconsoption. Более полное определение пакета можно найти здесь.

    Upload

    Загрузка одного файла.

    array(

           ‘type’  => ‘upload’,

           ‘value’ => array(

               /*

               ‘attachment_id’ => ‘9’,

               ‘url’ => ‘//site.com/wp-content/uploads/2014/02/whatever.jpg’

               */

               // Если значение установлено в коде, оно не рассматривается и не используется,

               // поскольку нет смысла устанавливать hardcode attachment_id

           ),

           ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

           ‘label’ => __(‘Label’, ‘{domain}’),

           ‘desc’  => __(‘Description’, ‘{domain}’),

           ‘help’  => __(‘Help tip’, ‘{domain}’),

           /**

            * Если установлено `true`, опция позволит загружать только изображения и отображать thumb выбранного.

            * Если установлено значение `false`, опция позволит загрузить любой файл из медиа-библиотеки.

            */

           ‘images_only’ => true,

           /**

            * Массив с разрешенными расширениями файлов, который будет фильтровать медиа-библиотеку и файлы для загрузки

            */

           ‘files_ext’ => array( ‘doc’, ‘pdf’, ‘zip’ ),

           /**

            * Массив с дополнительными типами mime, который не находится в массиве по умолчанию с mime-типами

            * из библиотеки Plustload javascript.Формат: массив (‘<mime-type>, <ext1> <ext2> <ext2>’).

            * Например: вы устанавливаете фильтр rar для фильтра, но фильтр игнорирует его, чем вы должны установить

            * Массив со следующим структурным массивом (‘.rar, rar’), и это решит проблему.

            */

           ‘extra_mime_types’ => array( ‘audio/x-aiff, aif aiff’ ) ),

    Custom Events

    fw:option-type:upload:change — Значение изменено.

    fw:option-type:upload:clear — Значение было очищено (выбранный элемент удален)

    Multi-Upload

    array(

           ‘type’  => ‘multi-upload’,

           ‘value’ => array(

               /*

               array(

                   ‘attachment_id’ => ‘9’,

                   ‘url’ => ‘//site.com/wp-content/uploads/2014/02/whatever.jpg’ ),

               …

               */

               // if value is set in code, it is not considered and not used

               // because there is no sense to set hardcode attachment_id

           ),

           ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

           ‘label’ => __(‘Label’, ‘{domain}’),

           ‘desc’  => __(‘Description’, ‘{domain}’),

           ‘help’  => __(‘Help tip’, ‘{domain}’),

           /**

            * Если установлено `true`, опция позволит загружать только изображения и отображать thumb выбранного.

            * Если установлено значение `false`, опция позволит загрузить любой файл из медиа-библиотеки.

            */

           ‘images_only’ => true,

           /**

            * Массив с разрешенными расширениями файлов, который будет фильтровать медиа-библиотеку и файлы для загрузки

            */

           ‘files_ext’ => array( ‘doc’, ‘pdf’, ‘zip’ ),

           /**

            * Массив с дополнительными типами mime, который не находится в массиве по умолчанию с mime-типами

            * из библиотеки Plustload javascript.Формат: массив (‘<mime-type>, <ext1> <ext2> <ext2>’).

            * Например: вы устанавливаете фильтр rar для фильтра, но фильтр игнорирует его, чем вы должны установить

            * Массив со следующим структурным массивом (‘.rar, rar’), и это решит проблему.

            */

           ‘extra_mime_types’ => array( ‘audio/x-aiff, aif aiff’ ) ),

    Custom Events

    fw:option-type:multi-upload:change — Значение изменено.

    fw:option-type:multi-upload:clear — Значение очищается (все выбранные элементы удаляются).

    fw:option-type:multi-upload:remove — thumb (выбранный элемент) будет удален. Срабатывает только тогда, когда для параметра images_only установлено значение true.

    Slider

    Перетащите маркер, чтобы выбрать числовое значение.

    array(

       ‘type’  => ‘slider’,

       ‘value’ => 33,

       ‘properties’ => array(

           /*

           ‘min’ => 0,

           ‘max’ => 100,

           ‘step’ => 1, // Set slider step. Always > 0. Could be fractional.

           */

       ),

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

    )

    Range Slider

    Перетащите маркер, чтобы выбрать числовое значение.

    array(

       ‘type’  => ‘range-slider’,

       ‘value’ => array(

           ‘from’ => 10,

           ‘to’   => 33, ),

       ‘properties’ => array(

           /*

           ‘min’ => 0,

           ‘max’ => 100,

           ‘step’ => 1, // Set slider step. Always > 0. Could be fractional.

           */

       ),

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’), )

    Popup

    Всплывающее окно с options.

    array(

       ‘type’ => ‘popup’,

       ‘value’ => array(

           ‘option_1’ => ‘value 1’,

           ‘option_2’ => ‘value 2’, ),

       ‘label’ => __(‘Popup’, ‘{domain}’),

       ‘desc’  => __(‘Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.’, ‘{domain}’),

       ‘popup-title’ => __(‘Popup Title’, ‘{domain}’),

       ‘button’ => __(‘Edit’, ‘{domain}’),

       ‘popup-title’ => null,

       ‘size’ => ‘small’, // small, medium, large

       ‘popup-options’ => array(

           ‘option_1’ => array(

               ‘label’ => __(‘Text’, ‘{domain}’),

               ‘type’ => ‘text’,

               ‘value’ => ‘Demo text value’,

               ‘desc’ => __(‘Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.’, ‘{domain}’),

               ‘help’ => sprintf(«%s \n\n’\»<br/><br/>\n\n <b>%s</b>»,

                   __(‘Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.’, ‘{domain}’),

                   __(‘Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium’, ‘{domain}’) ), ),

           ‘option_2’ => array(

               ‘label’ => __(‘Textarea’, ‘{domain}’),

               ‘type’ => ‘textarea’,

               ‘value’ => ‘Demo textarea value’,

               ‘desc’ => __(‘Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.’, ‘{domain}’),

               ‘help’ => sprintf(«%s \n\n’\»<br/><br/>\n\n <b>%s</b>»,

                   __(‘Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.’, ‘{domain}’),

                   __(‘Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium’, ‘{domain}’)

               ),  ), ), )

    Addable Popup

    Добавляемое всплывающее окно с options.

    array(

       ‘type’ => ‘addable-popup’,

       ‘value’ => array(

           array(

               ‘option_1’ => ‘value 1’,

               ‘option_2’ => ‘value 2’, ),

           // …

       ),

       ‘label’ => __(‘Addable Popup’, ‘{domain}’),

       ‘desc’  => __(‘Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.’, ‘{domain}’),

       ‘template’ => ‘{{- demo_text }}’,

       ‘popup-title’ => null,

       ‘size’ => ‘small’, // small, medium, large

       ‘limit’ => 0, // limit the number of popup`s that can be added

       ‘add-button-text’ => __(‘Add’, ‘{domain}’),

       ‘sortable’ => true,

       ‘popup-options’ => array(

           ‘option_1’ => array(

               ‘label’ => __(‘Text’, ‘{domain}’),

               ‘type’ => ‘text’,

               ‘value’ => ‘Demo text value’,

               ‘desc’ => __(‘Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.’, ‘{domain}’),

               ‘help’ => sprintf(«%s \n\n’\»<br/><br/>\n\n <b>%s</b>»,

                   __(‘Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.’, ‘{domain}’),

                   __(‘Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium’, ‘{domain}’)  ), ),

           ‘option_2’ => array(

               ‘label’ => __(‘Textarea’, ‘{domain}’),

               ‘type’ => ‘textarea’,

               ‘value’ => ‘Demo textarea value’,

               ‘desc’ => __(‘Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.’, ‘{domain}’),

               ‘help’ => sprintf(«%s \n\n’\»<br/><br/>\n\n <b>%s</b>»,

                   __(‘Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.’, ‘{domain}’),

                   __(‘Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium’, ‘{domain}’)

               ), ),  ), )

    Addable Option

    Создать список опций.

    array(

       ‘type’  => ‘addable-option’,

       ‘value’ => array(‘Value 1’, ‘Value 2’, ‘Value 3’),

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

       ‘option’ => array( ‘type’ => ‘text’ ),

       ‘add-button-text’ => __(‘Add’, ‘{domain}’),

       ‘sortable’ => true, )

    Custom Events

    fw:option-type:addable-option:option:init — Добавлена и инициализирована новая опция.

    Addable Box

    Добавить box с options.

    array(

       ‘type’  => ‘addable-box’,

       ‘value’ => array(

           array(

               ‘option_1’ => ‘value 1’,

               ‘option_2’ => ‘value 2’, ),

           // …

       ),

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

       ‘box-options’ => array(

           ‘option_1’ => array( ‘type’ => ‘text’ ),

           ‘option_2’ => array( ‘type’ => ‘textarea’ ), ),

       ‘template’ => ‘Hello {{- option_1 }}’, // box title

       ‘box-controls’ => array( // buttons next to (x) remove box button

           ‘control-id’ => ‘<small class=»dashicons dashicons-smiley»></small>’, ),

       ‘limit’ => 0, // limit the number of boxes that can be added

       ‘add-button-text’ => __(‘Add’, ‘{domain}’),

       ‘sortable’ => true, )

    Custom Events

    fw:option-type:addable-box:box:init — Box был инициализирован. Запускается для каждого существующего box после загрузки страницы или при добавлении box.

    fw:option-type:addable-box:control:click — Пользовательский элемент управления был нажат.

    Typography v2

    Выберите font family, style, weight, size, line-height, letter-spacing и color.

    array(

       ‘type’ => ‘typography-v2’,

       ‘value’ => array(

           ‘family’ => ‘Amarante’,

           // For standard fonts, instead of subset and variation you should set ‘style’ and ‘weight’.

           // ‘style’ => ‘italic’,

           // ‘weight’ => 700,

           ‘subset’ => ‘latin-ext’,

           ‘variation’ => ‘regular’,

           ‘size’ => 14,

           ‘line-height’ => 13,

           ‘letter-spacing’ => -2,

           ‘color’ => ‘#0000ff’ ),

       ‘components’ => array(

           ‘family’         => true,

           // ‘style’, ‘weight’, ‘subset’, ‘variation’ will appear and disappear along with ‘family’

           ‘size’           => true,

           ‘line-height’    => true,

           ‘letter-spacing’ => true,

           ‘color’          => true ),

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),)

    WP Editor

    array(

       ‘type’  => ‘wp-editor’,

       ‘value’ => ‘default value’,

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

       ‘size’ => ‘small’, // small, large

       ‘editor_height’ => 400,

       ‘wpautop’ => true,

       ‘editor_type’ => false, // tinymce, html

       /**

        * Also available

        * https://github.com/WordPress/WordPress/blob/4.4.2/wp-includes/class-wp-editor.php#L80-L94

        */

    )

    Multi-Picker

    Выберите вариант, а затем заполните options, связанные с этим выбором.

    Параметр picker содержит допустимый тип option с вариантами выбора. Поддерживаются следующие типы опций: select, radio, image-picker  и switch.

    array(

       ‘type’  => ‘multi-picker’,

       ‘label’ => false,

       ‘desc’  => false,

       ‘value’ => array(

           /**

            * ‘<custom-key>’ => ‘default-choice’

            */

           ‘gadget’ => ‘phone’,

           /**

            * These are the choices and their values,

            * they are available after option was saved to database

            */

           ‘laptop’ => array(

               ‘price’ => ‘123’,

               ‘webcam’ => false ),

           ‘phone’ => array(

               ‘price’ => ‘456’,

               ‘memory’ => ’32’ ) ),

       ‘picker’ => array(

           // ‘<custom-key>’ => option

           ‘gadget’ => array(

               ‘label’   => __(‘Choose device’, ‘{domain}’),

               ‘type’    => ‘select’, // or ‘short-select’

               ‘choices’ => array(

                   ‘phone’  => __(‘Phone’, ‘{domain}’),

                   ‘laptop’ => __(‘Laptop’, ‘{domain}’) ),

               ‘desc’    => __(‘Description’, ‘{domain}’),

               ‘help’    => __(‘Help tip’, ‘{domain}’), ) ),

       /*

       ‘picker’ => array(

           // ‘<custom-key>’ => option

           ‘gadget’ => array(

               ‘label’   => __(‘Choose device’, ‘{domain}’),

               ‘type’    => ‘radio’,

               ‘choices’ => array(

                   ‘phone’  => __(‘Phone’, ‘{domain}’),

                   ‘laptop’ => __(‘Laptop’, ‘{domain}’) ),

               ‘desc’    => __(‘Description’, ‘{domain}’),

               ‘help’    => __(‘Help tip’, ‘{domain}’), ) ),

       */

       /*

       ‘picker’ => array(

           // ‘<custom-key>’ => option

           ‘gadget’ => array(

               ‘label’   => __(‘Choose device’, ‘{domain}’),

               ‘type’    => ‘image-picker’,

               ‘choices’ => array(

                   ‘phone’  => ‘http://placekitten.com/70/70’,

                   ‘laptop’ => ‘http://placekitten.com/71/70’ ),

               ‘desc’    => __(‘Description’, ‘{domain}’),

               ‘help’    => __(‘Help tip’, ‘{domain}’), ) ),

       */

       /*

       picker => array(

           // ‘<custom-key>’ => option

           ‘gadget’ => array(

               ‘label’ => __(‘Choose device’, ‘{domain}’),

               ‘type’  => ‘switch’,

               ‘right-choice’ => array(

                   ‘value’ => ‘laptop’,

                   ‘label’ => __(‘Laptop’, ‘{domain}’) ),

               ‘left-choice’ => array(

                   ‘value’ => ‘phone’,

                   ‘label’ => __(‘Phone’, ‘{domain}’) ),

               ‘desc’ => __(‘Description’, ‘{domain}’),

               ‘help’ => __(‘Help tip’, ‘{domain}’), ) ),

       */

       ‘choices’ => array(

           ‘phone’ => array(

               ‘price’ => array(

                   ‘type’  => ‘text’,

                   ‘label’ => __(‘Price’, ‘{domain}’), ),

               ‘memory’ => array(

                   ‘type’  => ‘select’,

                   ‘label’ => __(‘Memory’, ‘{domain}’),

                   ‘choices’ => array(

                       ’16’ => __(’16Gb’, ‘{domain}’),

                       ’32’ => __(’32Gb’, ‘{domain}’),

                       ’64’ => __(’64Gb’, ‘{domain}’), ) ) ),

           ‘laptop’ => array(

               ‘price’ => array(

                   ‘type’  => ‘text’,

                   ‘label’ => __(‘Price’, ‘{domain}’),  ),

               ‘webcam’ => array(

                   ‘type’  => ‘switch’,

                   ‘label’ => __(‘Webcam’, ‘{domain}’), ) ), ),

       /**

        * (optional) if is true, the borders between choice options will be shown

        */

       ‘show_borders’ => false, )

    Get database option value

    $value = fw_get_db_…_option(

       ‘option_id/’. fw_get_db_…_option(‘option_id/’. ‘gadget’) );

    Map

    Google maps location.

    array(

       ‘type’  => ‘map’,

       ‘value’ => array(

           ‘coordinates’ => array(

               ‘lat’   => -34,

               ‘lng’   => 150, ) ),

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’), )

    Multi

    Группируйте значения любых options базы данных под одним ключом массива. Этот option не имеет дизайна, внутренние options будут выглядеть так же, как и другие options (это похоже на групповой контейнер).

    // database value structure

    ‘option_type_multi_id’ => array(

       ‘inner_option_1’ => …

       ‘inner_option_2’ => … )

    array(

       ‘type’  => ‘multi’,

       ‘value’ => array(

           ‘option-1’ => ‘value 1’,

           ‘option-2’ => ‘value 2’, ),

       ‘attr’  => array(

           ‘class’ => ‘custom-class’,

           ‘data-foo’ => ‘bar’,

           /*

           // Add this class to display inner options separators

           ‘class’ => ‘fw-option-type-multi-show-borders’,

           */

       ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

       ‘inner-options’ => array(

           ‘option_1’ => array( ‘type’ => ‘text’ ),

           ‘option_2’ => array( ‘type’ => ‘textarea’ ), ) )

    ВАЖНО

    Параметр, который содержит options, называется inner-options, а не options, иначе это будет рассматриваться как опция контейнера.

    Hidden

    Simple hidden input.

    array(

       ‘type’  => ‘hidden’,

       ‘value’ => ‘default value’,

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ), )

    HTML

    Если вы хотите отобразить custom часть html, используйте этот тип option.

    Этот тип option имеет значение, хранящееся в hidden input. Продвинутые пользователи могут создавать некоторые функции javascript в html и сохранять значение в этом hidden input.

    array(

       ‘type’  => ‘html’,

       ‘value’ => ‘default hidden value’,

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

       ‘html’  => ‘My <b>custom</b> <em>HTML</em>’, )

    Есть также типы опций html-fixed и html-full. Они такие же, как html, но имеют фиксированную и полную ширину опций.

    Password

    array(

       ‘type’  => ‘password’,

       ‘value’ => ‘default value’,

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’), )

    Oembed

    Сгенерируйте oembed предварительный просмотр вставленной ссылки, для получения дополнительной информации см. Embeds в WordPress.

    array(

       ‘type’  => ‘oembed’,

       ‘value’ => ‘https://vimeo.com/113078377’,

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’),

       ‘preview’ => array(

           ‘width’  => 300, // optional, if you want to set the fixed width to iframe

           ‘height’ => 300, // optional, if you want to set the fixed height to iframe

           /**

            * if is set to false it will force to fit the dimensions,

            * because some widgets return iframe with aspect ratio and ignore applied dimensions

            */

           ‘keep_ratio’ => true ) )

    Typography

    array(

       ‘type’  => ‘typography’,

       ‘value’ => array(

           ‘family’ => ‘Arial’,

           ‘size’   => 12,

           ‘style’  => ‘400’,

           ‘color’  => ‘#000000’ ),

      ‘components’ => array(

           ‘family’ => true,

           ‘size’   => true,

           ‘color’  => true ),

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’), )

    Icon

    Choose a FontAwesome icon.

    array(

       ‘type’  => ‘icon’,

       ‘value’ => ‘fa-smile-o’,

       ‘attr’  => array( ‘class’ => ‘custom-class’, ‘data-foo’ => ‘bar’ ),

       ‘label’ => __(‘Label’, ‘{domain}’),

       ‘desc’  => __(‘Description’, ‘{domain}’),

       ‘help’  => __(‘Help tip’, ‘{domain}’), )

    Create Option Type

    Чтобы определить новый тип параметра, создайте класс, который расширяет базовый класс типа и регистрирует его.

    Это не имеет значения, где вы поместите новый  option type. Если вы используете структуру каталогов Theme Includes, поместите ее в каталог {theme}/inc/includes/option-types/my-option/ и включите его в action fw_option_types_init:

    // file: {theme}/inc/hooks.php

    /** @internal */

    function _action_theme_include_custom_option_types() {

       require_once dirname(__FILE__) . ‘/includes/option-types/new/class-fw-option-type-new.php’; }

    add_action(‘fw_option_types_init’, ‘_action_theme_include_custom_option_types’);

    class FW_Option_Type_New extends FW_Option_Type
    {
       public function get_type()
       {
           return ‘new’; }

       /**
        * @internal
        */
       protected function _enqueue_static($id, $option, $data)
       {
           $uri = get_template_directory_uri() .‘/inc/includes/option-types/’. $this->get_type() .‘/static’;
           wp_enqueue_style(
               ‘fw-option-‘. $this->get_type(),
               $uri .‘/css/styles.css’ );
           wp_enqueue_script(
               ‘fw-option-‘. $this->get_type(),
               $uri .‘/js/scripts.js’,
               array(‘fw-events’, ‘jquery’) ); }
       /**
        * @internal
        */
       protected function _render($id, $option, $data)
       {
           /**
            * $data[‘value’] contains correct value returned by the _get_value_from_input()
            * You decide how to use it in html
            */
           $option[‘attr’][‘value’] = (string)$data[‘value’];
           /**
            * $option[‘attr’] contains all attributes.
            *
            * Main (wrapper) option html element should have «id» and «class» attribute.
            *
            * All option types should have in main element the class «fw-option-type-{$type}».
            * Every javascript and css in that option should use that class.
            *
            * Remaining attributes you can:
            *  1. use them all in main element (if option itself has no input elements)
            *  2. use them in input element (if option has input element that contains option value)
            *
            * In this case you will use second option.
            */
           $wrapper_attr = array(
               ‘id’    => $option[‘attr’][‘id’],
               ‘class’ => $option[‘attr’][‘class’], );
           unset(
               $option[‘attr’][‘id’],
               $option[‘attr’][‘class’] );
           $html  = ‘<div ‘. fw_attr_to_html($wrapper_attr) .‘>’;
           $html .= ‘<input ‘. fw_attr_to_html($option[‘attr’]) .‘ type=»text» />’;
           $html .= ‘<button type=»button» class=»button»>’. __(‘Clear text’, ‘{domain}’) .‘</button>’;
           $html .= ‘</div>’;
           return $html; }
       /**
        * @internal
        */
       protected function _get_value_from_input($option, $input_value)
       {
           /**
            * In this method you receive $input_value (from form submit or whatever)
            * and must return correct and safe value that will be stored in database.
            *
            * $input_value can be null.
            * In this case you should return default value from $option[‘value’]
            */
           if (is_null($input_value)) {
               $input_value = $option[‘value’]; }
           return (string)$input_value; }
       /**
        * @internal
        */
       protected function _get_defaults()
       {
           /**
            * These are default parameters that will be merged with option array.
            * They makes possible that any option has
            * only one required parameter array(‘type’ => ‘new’).
            */
           return array(
               ‘value’ => » ); } }
    FW_Option_Type::register(‘FW_Option_Type_New’);

    /**
    * Prefix (namespace) all css rules with «.fw-option-type-{$option_type}»
    * This guarantees that there will be no conflicts with other styles.
    */
    .fw-option-type-new input {
       background-color: green;
       color: white; }
    .fw-option-type-new button {
       display: block; }

    jQuery(document).ready(function ($) {
       var optionTypeClass = ‘.fw-option-type-new’;
       /**
        * Listen to special event that is triggered for uninitialized elements
        */
       fwEvents.on(‘fw:options:init’, function (data) {
           /**
            * data.$elements are jQuery selected elements
            * that contains options html that needs to be initialized
            *
            * Find uninitialized options by main class
            */
           var $options = data.$elements.find(optionTypeClass +‘:not(.initialized)’);
           /**
            * Listen for button click and clear input value
            */
           $options.on(‘click’, ‘button’, function(){
               $(this).closest(optionTypeClass).find(‘input’).val(»);  });
           /**
            * After everything has done, mark options as initialized
            */
           $options.addClass(‘initialized’); }); });

    Option Width

    Существует три типа ширины:

    • auto — динамически адаптируется к содержимому опции.
    • fixed — фиксированный размер .
    • full — полная доступная ширина (100%).

    Каждая опция имеет свой собственный тип ширины, указанный в FW_Option_Type::_get_backend_width_type().

    Custom Save Location

    По умолчанию параметры (post, settings, customizer, term и т. Д.) Сохраняются все в одном месте в базе данных, в wp_option или в любом другом месте. В некоторых случаях вам нужна опция для сохранения в отдельном wp_option или post meta или в другом настраиваемом месте в базе данных, например, option type Mailer settings сохраняется в одном wp_option и одно и то же значение используется во всех контактных формах. Это пользовательское поведение сохранения достигается через параметр опции fw-storage, он имеет следующую структуру:

    ‘option_id’ => array(

       ‘type’ => ‘any-type’,

       ‘fw-storage’ => array(

           ‘type’ => ‘valid-storage-type’,

           // Дополнительные параметры используемого типа хранилища

    ), )

    Когда options сохраняются и загружаются из базы данных, обрабатываются все их параметры хранения fw-storage

    Предопределенные типы

    Вот несколько примеров с типами хранения по умолчанию:

    1. Чтобы сохранить option в отдельном wp_option:

    ‘demo-option-id’ => array(

       ‘type’ => ‘text’,

       ‘fw-storage’ => array(

           ‘type’ => ‘wp-option’,

           ‘wp-option’ => ‘demo_wp_option’, ), )

    Добавьте вышеописанный массив параметров в настройках post, settings, customizer или term, сохраните форму и проверьте таблицу базы данных wp_options для опции с именем demo_wp_option.

    Чтобы сохранить option в отдельном post meta:

    ‘demo-option-id’ => array(

       ‘type’ => ‘text’,

       ‘fw-storage’ => array(

           ‘type’ => ‘post-meta’,

           ‘post-meta’ => ‘demo_post_meta’, ), )

    Добавьте вышеописанный массив параметров в post options, отредактируйте post и проверьте таблицу базы данных wp_postmeta для мета с именем demo_post_meta.

    Custom Types

    http://manual.unyson.io/en/latest/options/storage.html#content

    Categories : Word Press, www

    • « Previous Post
    • Next Post »

    Comments are closed.

    • Word Press
      • #1. Introduction to WordPress
      • #2. WordPress Files Configuration
      • #3. Kernel Review. Codex
      • #4. Standards of Encoding
      • #5. Develop a plugin, introduction
      • #6. Hooks, Filters, InterNation
      • #7. Adding Admin Menus, JS, CSS
      • #8. HTTP API, Shortcodes, Transients
      • #9. Options API, Settings API
      • #10. Database API, $wpdb object
      • #11. Ajax. Widget API. Dashboard API
      • #12. Post Type. Taxonomies. Metadata
      • #13. Theme Development. Basics
      • #14. Loop. Template. WP_Query
      • Lecture #15. functions.php – I
      • Lecture #16. functions.php – II
      • #17. Child Theme. Shortcode. TinyMCE
      • #18. Frameworks. Blank Theme
      • #19. Framework. Underscores. Unyson
      • #20: Framework Unyson. Options
      • #21. Extensions, Components, Manifest
      • #22. Unyson: Built-in Extensions
      • #23. Unyson: Helpers, Filters & Actions
      • #24. WC: Installation & Updating
      • #25. WC: Settings & Options
      • #26. WC: Product Setup
      • #27. WC: Sell Products, Order
      • #28. WC: Theming
      • #29. WC: Extending
      • #30. WC: Extending
    • CSS
      • ПРОГРАММИРОВАНИЕ (CODING)
      • Emmet, ul, li, table, form
      • Style, hover, child
      • CSS Hat, font, background
      • Reset, margin, padding, float
      • Base64, relative, z-index
      • Google Fonts, PSD
      • Brackets, Bootstrap
      • Script, src, comments
      • jQuery, Slick Js, Tooltip
      • Bootstrap, Slick Nav, @media
      • Mobile Vew, Font Awesome
      • Flexbox, Slider
      • SASS, Bootstrap
    • Cron
    • Framework Yii2
    • React, Angular
    • JavaScript
    • Freelance

    Generic selectors
    Exact matches only
    Search in title
    Search in content
    Search in posts
    Search in pages
    Filter by Categories
    CSS
    JavaScript
    Word Press
    www

    2019 Rostyslav N Design © Уроки программирования