По поводу хука Contact Form 7 (древовидного списка)
Сделал по Вашему решению (модификации) Contact Form 7 - древовидный список.По этому коду
Все работает но вот нельзя Выбрать в качестве типа - заголовок категории списка. Вот видео где показана суть вопроса и того как бы хотелось сделать. ссылка
Вопрос: Как сделать чтобы можно было выбрать и родительские категории списка ? Надо в коде том что внизу этой статьи >изменить ? Можете подсказать как ? Заранее спасибо.
Вот источник кода которий добавил функционал списка категорий
<?php
/**
* Добавляем новый тег select_optgroup
*
* @return void
*/
function wpcf7_add_form_tag_select_group(){
wpcf7_add_form_tag( array('select_optgroup','select_optgroup*'), 'wpcf7_select_optgroup_form_tag_handler', true );
}
add_action( 'wpcf7_init', 'wpcf7_add_form_tag_select_group', 9 ); // 9 - до регистрации остальных тегов формы
/**
* Создание html версии выпадающего списка с группировкой option
*
* @param array $tag Атрибуты поля [select_optgroup]
*
* @return string html код поля
*/
function wpcf7_select_optgroup_form_tag_handler( $tag ){
$tag = new WPCF7_FormTag( $tag );
if( empty( $tag->name ) ){
return '';
}
$validation_error = wpcf7_get_validation_error( $tag->name );
$class = wpcf7_form_controls_class( $tag->type );
if( $validation_error ){
$class .= ' wpcf7-not-valid';
}
$atts = array();
$atts['class'] = $tag->get_class_option( $class );
$atts['id'] = $tag->get_id_option();
$atts['tabindex'] = $tag->get_option( 'tabindex', 'int', true );
if( $tag->is_required() ){
$atts['aria-required'] = 'true';
}
$atts['aria-invalid'] = $validation_error ? 'true' : 'false';
$multiple = $tag->has_option( 'multiple' );
$include_blank = $tag->has_option( 'include_blank' );
$first_as_label = $tag->has_option( 'first_as_label' );
$values = $tag->values;
$labels = $tag->labels;
if( $data = (array) $tag->get_data_option() ){
$values = array_merge( $values, array_values( $data ) );
$labels = array_merge( $labels, array_values( $data ) );
}
$defaults = array();
$default_choice = $tag->get_default_option( null, 'multiple=1' );
foreach( $default_choice as $value ){
$key = array_search( $value, $values, true );
if( false !== $key ){
$defaults[] = (int) $key + 1;
}
}
if( $matches = $tag->get_first_match_option( '/^default:([0-9_]+)$/' ) ){
$defaults = array_merge( $defaults, explode( '_', $matches[1] ) );
}
$defaults = array_unique( $defaults );
$shifted = false;
if( $include_blank || empty( $values ) ){
array_unshift( $labels, '---' );
array_unshift( $values, '' );
$shifted = true;
}
elseif( $first_as_label ){
$values[0] = '';
}
$html = '';
$hangover = wpcf7_get_hangover( $tag->name );
foreach( $values as $key => $value ){
$selected = false;
if( $hangover ){
if( $multiple ){
$selected = in_array( esc_sql( $value ), (array) $hangover );
}
else{
$selected = ( $hangover == esc_sql( $value ) );
}
}
else{
if( ! $shifted && in_array( (int) $key + 1, (array) $defaults ) ){
$selected = true;
}
elseif( $shifted && in_array( (int) $key, (array) $defaults ) ){
$selected = true;
}
}
$item_atts = array(
'value' => $value,
'selected'=> $selected ? 'selected' : ''
);
$item_atts = wpcf7_format_atts( $item_atts );
$label = isset($labels[$key]) ? $labels[$key] : $value;
// Если в лейбле содержится текст 'optgroup-', то открываем группу
if( $label{0} == '{' ){
$html .= '<optgroup label="'. substr( $label, 1 ) .'">';
}
// Если в лейбле содержится текст 'endoptgroup', то закрываем группу
elseif( $label == '}' ){
$html .= '</optgroup>';
}
// Если в лейбле не нашлись теги открытия или закрыия группы, значит это обычный лейб и не обрабатываем его
else {
$html .= sprintf( '<option %1$s>%2$s</option>', $item_atts, esc_html( $label ) );
}
}
if( $multiple ) $atts['multiple'] = 'multiple';
$atts['name'] = $tag->name . ( $multiple ? '[]' : '' );
$atts = wpcf7_format_atts( $atts );
$html = sprintf('<span class="wpcf7-form-control-wrap %1$s"><select %2$s>%3$s</select>%4$s</span>',
sanitize_html_class($tag->name), $atts, $html, $validation_error );
return $html;
}
/**
* Создаем кнопку "Сгрупированный выпадающий список" в панели составления шаблона формы
*
* Значение "menu" можно изменить на любое, оно будет поставлено в генераторе тега в поле "Имя"
*
* @return void
*/
function wpcf7_add_tag_generator_select_optgroup(){
$tag_generator = WPCF7_TagGenerator::get_instance();
$tag_generator->add( 'selectgroup', 'Выпадающий список (с группами)', 'wpcf7_tag_generator_select_optgroup' );
}
add_action( 'wpcf7_admin_init', 'wpcf7_add_tag_generator_select_optgroup', 25 );
/**
* Формирование кнопки и модального окна для удобного создания тега поля
*
* @param object $contact_form объект формы со всеми настройками и параметрами
* @param array $args массив с параметрами кнопки id, title, content
*
*/
function wpcf7_tag_generator_select_optgroup( $contact_form, $args = '' ){
$args = wp_parse_args( $args, array() );
$description = "Можно создавать группы, для этого оберните опции в конструкцию: '{Название_группы ...опции... }' (все на новой строке). Подробнее см. %s.";
$desc_link = wpcf7_link( '//wp-kama.ru/met/contact-form-7', 'всё о плагине Contact Form 7' );
$description = sprintf( $description, $desc_link );
?>
<div class="control-box">
<fieldset>
<table class="form-table">
<tbody>
<tr>
<th scope="row">
<?php echo esc_html( __( 'Field type', 'contact-form-7' ) ); ?>
</th>
<td>
<fieldset>
<legend class="screen-reader-text">
<?php echo esc_html( __( 'Field type', 'contact-form-7' ) ); ?>
</legend>
<label>
<input type="checkbox" name="required" /> <?php echo esc_html( __( 'Required field', 'contact-form-7' ) ); ?>
</label>
</fieldset>
</td>
</tr>
<tr>
<th scope="row">
<label for="<?php echo esc_attr( $args['content'] . '-name' ); ?>">
<?php echo esc_html( __( 'Name', 'contact-form-7' ) ); ?>
</label>
</th>
<td>
<input type="text" name="name" class="tg-name oneline" id="<?php echo esc_attr( $args['content'] . '-name' ); ?>" />
</td>
</tr>
<tr>
<th scope="row">
<?php echo esc_html( __( 'Options', 'contact-form-7' ) ); ?>
</th>
<td>
<fieldset>
<legend class="screen-reader-text">
<?php echo esc_html( __( 'Options', 'contact-form-7' ) ); ?>
</legend>
<textarea name="values" class="values" id="<?php echo esc_attr( $args['content'] . '-values' ); ?>"></textarea>
<label for="<?php echo esc_attr( $args['content'] . '-values' ); ?>">
<span class="description">
<?php echo esc_html( __( "One option per line.", 'contact-form-7' ) ) .'<br>'. $description; ?>
</span>
</label><br />
<label>
<input type="checkbox" name="multiple" class="option" /> <?php echo esc_html( __( 'Allow multiple selections', 'contact-form-7' ) ); ?>
</label><br />
<label>
<input type="checkbox" name="include_blank" class="option" /> <?php echo esc_html( __( 'Insert a blank item as the first option', 'contact-form-7' ) ); ?>
</label>
</fieldset>
</td>
</tr>
<tr>
<th scope="row">
<label for="<?php echo esc_attr( $args['content'] . '-id' ); ?>">
<?php echo esc_html( __( 'Id attribute', 'contact-form-7' ) ); ?>
</label>
</th>
<td>
<input type="text" name="id" class="idvalue oneline option" id="<?php echo esc_attr( $args['content'] . '-id' ); ?>" />
</td>
</tr>
<tr>
<th scope="row">
<label for="<?php echo esc_attr( $args['content'] . '-class' ); ?>">
<?php echo esc_html( __( 'Class attribute', 'contact-form-7' ) ); ?>
</label>
</th>
<td>
<input type="text" name="class" class="classvalue oneline option" id="<?php echo esc_attr( $args['content'] . '-class' ); ?>" />
</td>
</tr>
</tbody>
</table>
</fieldset>
</div>
<div class="insert-box">
<!-- Обязательно вписываем в значение name название поля, в нашем случае select_optgroup, чтобы оно подставлялось по клику автоматически -->
<input type="text" name="select_optgroup" class="tag code" readonly="readonly" onfocus="this.select()" />
<div class="submitbox">
<input type="button" class="button button-primary insert-tag" value="<?php echo esc_attr( __( 'Insert Tag', 'contact-form-7' ) ); ?>" />
</div>
<br class="clear" />
<p class="description mail-tag">
<label for="<?php echo esc_attr( $args['content'] . '-mailtag' ); ?>">
<?php echo sprintf( esc_html( __( "To use the value input through this field in a mail field, you need to insert the corresponding mail-tag (%s) into the field on the Mail tab.", 'contact-form-7' ) ), '<strong><span class="mail-tag"></span></strong>' ); ?><input type="text" class="mail-tag code hidden" readonly="readonly" id="<?php echo esc_attr( $args['content'] . '-mailtag' ); ?>" />
</label>
</p>
</div>
<?php
}Заметки к вопросу:
При использовании optgroup такого не достичь, спецификация не даёт. Надо по ходу делать просто с отступами, как это делает функция wp_dropdown_pages() и подобные. Там получается подобная вёрстка: