0

So, I've created custom markup for a menu. The functionality of the menu is built like so...

<?php 
  $parent = array();
    if (($locations = get_nav_menu_locations()) && isset($locations[$menu_name])){
      $menu = wp_get_nav_menu_object($locations[$menu_name]);
      $menu_items = wp_get_nav_menu_items($menu->term_id);
      $parent_id = 0;

    foreach((array)$menu_items as $key => $menu_item){
      if($menu_item->menu_item_parent == 0) { 
        $parent_id = $menu_item->db_id;
        $title = $menu_item->title;
        $url = $menu_item->url;
        $target = $menu_item->target;
        $class = $menu_item->classes;
        array_push($parent, array("title" => $title, "url" => $url, "target" => $target, "class" => $class));
    }
    else if($menu_item->menu_item_parent == $parent_id){
      $title = $menu_item->title;
      $url = $menu_item->url;
      $target = $menu_item->target;
      $class = $menu_item->classes;
      array_push($parent[count($parent) - 1]["child"], array("title" => $title, "url" => $url, "target" => $target, "class" => $class));
    }
    else{}
    }
  }

And the actual markup/output is built this way...

  foreach ($parent as $key => $value){
    if(empty($value["child"])){
      echo "<a href='" . $value["url"] . "' target='" . $value["target"] . "' class='" . $value["class"] . "'>" . $value["title"] . "</a>";
    }
    else
    {
    }
  }

However, I need to be able to access the custom class for the menu items in the code. Right now, using $class = $menu_item->classes; I get a class output, but it's simply class="Array".

Can anyone help me figure out how to split the classes and get the custom class to output into my markup?

  • 1
    Looks like $value["class"] is an array, so try imploding it: echo "<a href='" . $value["url"] . "' target='" . $value["target"] . "' class='" . implode( " ", $value["class"] ) . "'>" . $value["title"] . "</a>"; – Samuel Elh Jun 6 '16 at 17:54
  • Tried that, all I got was this. Warning: implode(): Invalid arguments passed – Jesse Winton Jun 6 '16 at 18:02
1

What you're getting is an array so you need to implode() them - the Walker_Nav_Menu has something like this:

$class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );

So you can modify your foreach to implode them in a similar fashion

$class = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $menu_item->classes ), $menu_item) ) );

We still want to make sure that the nav_menu_css_class gets applied in case modifications has been made form that hook.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.