How to add data-attribute to li element for nav_menu

时间:2017-08-05 11:51:47

标签: wordpress wordpress-theming

How can I correctly add data-attribute to li which is inside specific ul with class .portfolio_nav. When I'm using getElementByTagName it add data-attribute to all li elements on pages, but when I use xpath and specify that I need li inside specific class it doesn't add any class.

Here is my code:

function addDataAttr( $items, $args ) {
    $internalErrors = libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML($items);
    libxml_use_internal_errors($internalErrors);
    $xpath = new DOMXpath($dom);
    $find = $xpath->query('//ul[contains(@class, "nav_portfolio")]/li');
    //$find = $dom->getElementsByTagName('li'); -> working example

    foreach ($find as $item ) {
        $item->setAttribute('data-filter','office');
    }

    return $dom->saveHTML();
}
add_filter('wp_nav_menu_items', 'addDataAttr', 20, 2); 

Navigation:

<nav class="portfolio-nav portfolio-nav-head hidden-xs"> 
      <div class="filter_div controls row"> 
       <ul class="nav_portfolio"> 
            <li class="col-xs-6 col-sm-6 col-md-2 filter active"><a href="#" class="scrollIt">Office</a></li> 
           <li class="col-xs-6 col-sm-6 col-md-2 filter"><a href="#" class="scrollIt">Bedroom</a></li>
      </ul>  
  </div> 
 </nav>

1 个答案:

答案 0 :(得分:2)

我希望这会帮助你。我想你需要首先找到具有特定类名的ul,然后添加数据属性。

    <?php
   function addDataAttr( $items, $args ) {
$internalErrors = libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($items);
libxml_use_internal_errors($internalErrors);
$find = $dom->getElementsByTagName('ul');//find tag name with ul first
foreach ($find as $item ) {
    //check if ul has class attribute first
    if($item->hasAttribute('class')){
        //get class name 
         $className = $item->getAttribute('class');
    //if more than one class name use php explode function otherwise check with class name 
    $classes = explode(' ',$className);
    if(in_array('nav_portfolio',$classes)){
        //if match than use foreach for child li and add attribute you want to addd
        foreach($item->childNodes as $cNode){
            $cNode->setAttribute('data-filter','office');
        }

        }
    }
}

return $dom->saveHTML();
}
  echo addDataAttr('<ul><li> </li> <li> </li> </ul><ul class ="nav_portfolio"><li> </li><li> </li></ul>',array()); 
   // or your hook