0

Есть вот такая функция для function.php файла, которая позволяет добавлять кнопку в меню, если есть потомки


//// Добавление  произвольного элемента в меню
add_filter('walker_nav_menu_start_el', 'add_button_for_mobile', 10, 4);
function add_button_for_mobile($item_output, $item, $depth, $args)
{

    global $wpdb;
    $has_children = $wpdb->get_var("SELECT COUNT(meta_id) FROM {$wpdb->prefix}postmeta WHERE meta_key='_menu_item_menu_item_parent' AND meta_value='" . $item->ID . "'");
    if ($has_children) {
        $item_output = '<button class="btn_nav__mobil" type="button" aria-label="Düğme alt menüsü"></button>' . $item_output; // Add custom elements
    }
    return $item_output;
}

Подскажите, пожалуйста как переписать эту функцию, что бы вместо кнопки у меня выводился input потом список потом label ... *Делаю AMP версию, там JS запрещён, хочу прокинуть слайд эффект через событие :checked и CSS

Пробую так, написать

//// Добавление  произвольного элемента в меню
add_filter('walker_nav_menu_start_el', 'add_button_for_mobile', 10, 4);
function add_button_for_mobile($item_output, $item, $depth, $args)
{

    global $wpdb;
    $has_children = $wpdb->get_var("SELECT COUNT(meta_id) FROM {$wpdb->prefix}postmeta WHERE meta_key='_menu_item_menu_item_parent' AND meta_value='" . $item->ID . "'");
    if ($has_children) {
        $item_output = '<input class="btn_nav__mobil__checkbox" id="mob-'. $item->ID .'" type="checkbox">' . $item_output . '<label class="btn_nav__mobil" for="mob-'. $item->ID .'"></label>'; // Add custom elements
    }
    return $item_output;
}

Но это выдает не ту раскладку введите сюда описание изображения

<nav class="menu_second">
            <?php wp_nav_menu([
                    'theme_location' => 'navigation_menu',
                    'container' => false,
                    'fallback_cb' => '',
                    'echo' => 1,
                    'container_class' => '',
                    'menu_class' => 'menu_second__list bl_nav__list',
                    'items_wrap' => '<ul class="%2$s">%3$s</ul>',
                    'walker' => new Custom_Walker_Nav_Menu()
                ]
            ); ?>
        </nav>
2
  • сделайте свой walker класс и переопределите в нем метод end_lvl и start_lvl
    – Darth KYL
    3 фев 2022 в 11:22
  • можешь подсказать как это расписать ? я не очень силен в php 3 фев 2022 в 12:19

1 ответ 1

3

Думаю вот так может выглядеть класс в вашем случае, не забудьте объявить свой walker при вызове wp_nav_menu

class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {

    private $item_id = [];

    public function start_el( &$output, $item, $depth = 0, $args = null, $id = 0 ) {
        if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
            $t = '';
            $n = '';
        } else {
            $t = "\t";
            $n = "\n";
        }
        $indent = ( $depth ) ? str_repeat( $t, $depth ) : '';

        $classes   = empty( $item->classes ) ? array() : (array) $item->classes;
        $classes[] = 'menu-item-' . $item->ID;

        $args = apply_filters( 'nav_menu_item_args', $args, $item, $depth );

        $class_names = implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );
        $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

        $id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args, $depth );
        $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

        $output .= $indent . '<li' . $id . $class_names . '>';

        $atts           = array();
        $atts['title']  = ! empty( $item->attr_title ) ? $item->attr_title : '';
        $atts['target'] = ! empty( $item->target ) ? $item->target : '';
        if ( '_blank' === $item->target && empty( $item->xfn ) ) {
            $atts['rel'] = 'noopener';
        } else {
            $atts['rel'] = $item->xfn;
        }
        $atts['href']         = ! empty( $item->url ) ? $item->url : '';
        $atts['aria-current'] = $item->current ? 'page' : '';

        $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );

        $attributes = '';
        foreach ( $atts as $attr => $value ) {
            if ( is_scalar( $value ) && '' !== $value && false !== $value ) {
                $value       = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
                $attributes .= ' ' . $attr . '="' . $value . '"';
            }
        }

        $title = apply_filters( 'the_title', $item->title, $item->ID );

        $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );

        $item_output = '';

        if ( in_array( 'menu-item-has-children', $item->classes ) ) {
            $this->item_id[$depth] = $item->ID;

            $item_output .= '<input class="btn_nav__mobil__checkbox" id="mob-'. $item->ID .'" type="checkbox">'; // Add custom elements
        }

        $item_output .= $args->before;
        $item_output .= '<a' . $attributes . '>';
        $item_output .= $args->link_before . $title . $args->link_after;
        $item_output .= '</a>';
        $item_output .= $args->after;

        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }

    public function end_lvl( &$output, $depth = 0, $args = null ) {
        if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
            $t = '';
            $n = '';
        } else {
            $t = "\t";
            $n = "\n";
        }
        $indent  = str_repeat( $t, $depth );
        $output .= "$indent</ul>{$n}";

        if ( isset( $this->item_id[ $depth ] ) ) {
            $output .= '<label class="btn_nav__mobil" depth="' . $depth . '" for="mob-' . $this->item_id[ $depth ] . '"</label>';
        }
    }
}
7
  • Чёт подключил, в меню (код добавил в вопрос), но инициализация дополнительних элементов не произошла, не понимаю как это дело дебажить 3 фев 2022 в 14:38
  • а куда добавили сам класс?
    – Darth KYL
    3 фев 2022 в 15:06
  • function.php файл 3 фев 2022 в 15:07
  • как вариант вы можете сделать var_dump(1234) допустим в методе start_el, если на фронте не появятся 1234 то вы неправильно подключили класс либо не к тому меню
    – Darth KYL
    3 фев 2022 в 15:14
  • 1
    похоже что у вас переопределяются классы пункта меню, вы можете в методе start_el найти условие if ( in_array( 'menu-item-has-children', $item->classes ) ) { и заменить его на это global $wpdb; $has_children = $wpdb->get_var("SELECT COUNT(meta_id) FROM {$wpdb->prefix}postmeta WHERE meta_key='_menu_item_menu_item_parent' AND meta_value='" . $item->ID . "'"); if ($has_children) {
    – Darth KYL
    3 фев 2022 в 15:22

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.