source

WordPress의 "wp_nav_menu" 서브메뉴에서 클래스 및 요소를 태그에 추가하는 방법

nicesource 2023. 2. 10. 22:03
반응형

WordPress의 "wp_nav_menu" 서브메뉴에서 클래스 및 요소를 태그에 추가하는 방법

클래스를 추가하려고 합니다.a의 태그sub-menu및 ab태그를 지정합니다.

WordPress는 다음과 같은 코드를 제공합니다.

<li id="menu-item-72" class="menu-item menu-item-type-post_type menu-item-object-page dropdown menu-item-72"><a
    href="#">Link</a>
  <ul class="dropdown-menu"></ul>

그리고 난 이걸 원해:

<li id="menu-item-72" class="menu-item menu-item-type-post_type menu-item-object-page dropdown menu-item-72"> <a
    href="#" class="dropdown-toggle" data-toggle="dropdown">Link <b class="caret"></b></a>
  <ul class="dropdown-menu"></ul>

그것에 대한 해결책을 아는 사람 있나요?

이 답변에서는 워드프레스 메뉴에 커스텀HTML을 추가하는 방법에 대해 설명합니다.https://stackoverflow.com/a/12251157/1627227

편집:

당신의 질문에 맞게 예를 들어봤습니다.functions.php에 배치할 수 있습니다.코멘트는 커스텀코드를 추가하는 장소에 대해 설명합니다.

class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {

  function start_lvl(&$output, $depth) {
      $indent = str_repeat("\t", $depth);
      //$output .= "\n$indent<ul class=\"sub-menu\">\n";

      // Change sub-menu to dropdown menu
      $output .= "\n$indent<ul class=\"dropdown-menu\">\n";
  }

  function start_el ( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
    // Most of this code is copied from original Walker_Nav_Menu
    global $wp_query, $wpdb;
    $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

    $class_names = $value = '';

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

    $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
    $class_names = ' class="' . esc_attr( $class_names ) . '"';

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

    $has_children = $wpdb->get_var("SELECT COUNT(meta_id)
                            FROM wp_postmeta
                            WHERE meta_key='_menu_item_menu_item_parent'
                            AND meta_value='".$item->ID."'");

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

    $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
    $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
    $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
    $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';

    // Check if menu item is in main menu
    if ( $depth == 0 && $has_children > 0  ) {
        // These lines adds your custom class and attribute
        $attributes .= ' class="dropdown-toggle"';
        $attributes .= ' data-toggle="dropdown"';
    }

    $item_output = $args->before;
    $item_output .= '<a'. $attributes .'>';
    $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;

    // Add the caret if menu level is 0
    if ( $depth == 0 && $has_children > 0  ) {
        $item_output .= ' <b class="caret"></b>';
    }

    $item_output .= '</a>';
    $item_output .= $args->after;

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

}

이 설정을 완료하면 메뉴가 표시되는 지점까지 이동)으로 이동해야 합니다.wp_nav_menu())가 호출됩니다.제가 링크한 답변에는 다음과 같은 전체 기능 호출이 있습니다.wp_nav_menu단, 다음 행을 추가해야 합니다.'walker' => new Custom_Walker_Nav_Menu특정 메뉴에서 사용자 지정 워커 개체를 사용하려면 Arguments 배열로 이동합니다.

이해하셨기를 바랍니다;)

Wordpress 3.6.0 이후 nav_menu_link_attributes 필터를 사용할 수 있습니다.

add_filter( 'nav_menu_link_attributes', 'add_class_to_items_link', 10, 3 );

function add_class_to_items_link( $atts, $item, $args ) {
  // check if the item has children
  $hasChildren = (in_array('menu-item-has-children', $item->classes));
  if ($hasChildren) {
    // add the desired attributes:
    $atts['class'] = 'dropdown-toggle';
    $atts['data-toggle'] = 'dropdown';
    $atts['data-target'] = '#';
  }
  return $atts;
}

유감스럽게도 태그에는 사용할 수 있는 필터가 없기 때문에 워커가 필요합니다.

class MY_Menu_Walker extends Walker_Nav_Menu {

  public function start_lvl( &$output, $depth = 0, $args = array() ) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<ul class=\"sub-menu dropdown-menu\">\n";
  }   

}

메뉴를 호출할 때 워커 옵션을 추가합니다.

wp_nav_menu( array('walker' => new MY_Menu_Walker)); 

이 코드를 기능에서 사용합니다.php

function add_menuclass($ulclass) {
   return preg_replace('/<a /', '<a class="list-group-item"', $ulclass);
}
add_filter('wp_nav_menu','add_menuclass');

이를 사용하여 하위 메뉴가 있는지 확인할 수 있습니다.

$has_children = $wpdb->get_var("SELECT COUNT(meta_id)
                                FROM wp_postmeta
                                WHERE meta_key='_menu_item_menu_item_parent'
                                AND meta_value='".$item->ID."'");

그럼 간단하게 체크해 주세요.

if ( $has_children > 0 ) {
  // These lines adds your custom class and attribute
  $attributes .= ' class="dropdown-toggle"';
  $attributes .= ' data-toggle="dropdown"';
}

$wpdb를 글로벌로 설정하는 것을 잊지 마십시오.

global $wp_query, $wpdb;

짜잔~

functions.php에 배치할 수 있습니다.

class My_Walker_Nav_Menu extends Walker_Nav_Menu {
    function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ){
      $GLOBALS['dd_children'] = ( isset($children_elements[$element->ID]) )? 1:0;
      $GLOBALS['dd_depth'] = (int) $depth;
      parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
    }
   function start_lvl(&$output, $depth) {
     $indent = str_repeat("\t", $depth);
     $output .= "\n$indent<ul class=\"dropdown-menu\">\n";
   }
  function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) 
  {
    global $wp_query, $wpdb;
    $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
    $li_attributes = '';
    $class_names = $value = '';
    $classes = empty( $item->classes ) ? array() : (array) $item->classes;

    //Add class and attribute to LI element that contains a submenu UL.
    if ($args->has_children){
      $classes[]    = 'dropdown';
      $li_attributes .= 'data-dropdown="dropdown"';
    }
    $classes[] = 'menu-item-' . $item->ID;
    //If we are on the current page, add the active class to that menu item.
    $classes[] = ($item->current) ? 'active' : '';
    //Make sure you still add all of the WordPress classes.
    $class_names = join( ' ', apply_filters( 'nav_menu_css_class',     array_filter( $classes ), $item, $args ) );
    $class_names = ' class="' . esc_attr( $class_names ) . '"';
    $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
    $id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : '';
    $has_children = $wpdb->get_var(
    $wpdb->prepare("
       SELECT COUNT(*) FROM $wpdb->postmeta
       WHERE meta_key = %s
       AND meta_value = %d
       ", '_menu_item_menu_item_parent', $item->ID)
     );
   $output .= $indent . '<li' . $id . $value . $class_names .'>';
   $output .= $indent . '<li' . $id . $value . $class_names . $li_attributes . '>';
   //Add attributes to link element.
   $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
   $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target     ) .'"' : '';
   $attributes .= ! empty( $item->xfn ) ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
   $attributes .= ! empty( $item->url ) ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
   // Check if menu item is in main menu

if ( $depth == 0 && $has_children > 0  ) {
    // These lines adds your custom class and attribute
    $attributes .= ' class="dropdown-toggle"';
    $attributes .= ' data-toggle="dropdown"';
}
   $item_output = $args->before;
   $item_output .= '<a'. $attributes .'>';
   $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
   // Add the caret if menu level is 0
   if ( $depth == 0 && $has_children > 0  ) {
      $item_output .= ' <b class="caret"></b>';
   }
   $item_output .= '</a>';
   $item_output .= $args->after;
   $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
  }
}

그런 다음 이 메뉴를 표시할 템플릿에서 이 코드를 입력합니다.

   <?php

                if ( has_nav_menu( 'primary' ) ) {

                     $defaults = array(
                        'theme_location'  => 'primary',
                        //'menu'            => '',
                         'container'       => 'ul',
                         'container_class' => '',
                         'container_id'    => '',
                         'menu_class'      => '',
                         'menu_id'         => '',
                         'walker'          =>  new My_Walker_Nav_Menu()
                    );

                    wp_nav_menu( $defaults );

                }
            ?> 

이걸로 문제를 해결했어요.

언급URL : https://stackoverflow.com/questions/13161201/how-to-add-class-and-element-to-a-tag-in-sub-menu-of-wp-nav-menu-in-wordpres

반응형