PHP multidimensional array recursion problem [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Walk array recursively and print the path of the walk
Anyone can help me on this code?
<?php
function buildMenuWalk(&$array, &$depth, $currentDepth = 1)
{
# start new level html
$html = '';
# walk till the depth defined on the config
if($currentDepth > $depth)
{
return null;
}
# loop through all items in this level
foreach($array as $key => &$value)
{
# if not in area map continue
if(!is_numeric($key))
{
continue;
}
# if no <li> has been created yet, open the <ul>
$html .= empty( $html ) ? '<ul class="dropdown">' : '';
#extract the label from this level's array, designated by $labelKey
$label = isset( $value['areaname'] ) ? $value['areaname'] : '';
# open an <li>
$html .= '<li>';
# generate url
$url = '';
if($currentDepth == $depth)
{
$url = ' href="'.
$url .= '"';
}
# construct content inside the <li>
$html .= '<a' . $url .'>' . $label . '</a>';
# run the function again to grab children levels
if(is_array($value))
{
$html .= buildMenuWalk($value, $depth, $currentDepth + 1);
}
# close <li>
$html .= '</li>';
}
# close <ul> if was generated content on this level
$html .= !empty( $html ) ? '</ul>' : '';
return $html;
}
$depth = 2;
$config['content']['map'][1]['areaname'] = 'area_1';
$config['content']['map'][1][1]['areaname'] = 'block_1';
$config['content']['map'][2]['areaname'] = 'area_2';
$config['content']['map'][2][1]['areaname'] = 'block_1';
$config['content']['map'][2][2]['areaname'] = 'bloack_2';
echo buildMenuWalk($config['content']['map'], $depth);
?>
If you check the code above, Im using to display a menu recursively ...
If the script identify the menu reached the depth, will display href="" inside the tag. Inside this href I want add all parent areas on the recursion.
For example:
$config['content']['map'][2]['areaname'] = 'area_2';
$config['content']['map'][2][1]['areaname'] = 'block_1';
$config['content']['map'][2][2]['areaname'] = 'bloack_2';
When script reaches the bloack_2, I need display:
<a href="area_2=2&block_2=2">
Since its a multidimensional array and can grow to like 4-5 dimension, the output href should count all these levels. For example area_2=1&block_10=5&sub_area_1=5&section_7=8 ...
I probably need some array to store all href path during the recursion, but I cant figure how to do it.
Thanks,
PS: The script will be used to build a dropdown menu. The parent levels don't need to be linked, so print the tag will display the child menu. The last child, will be linked, but need contain all parent params so the results can be filtered.
Link to the code running and returning values:
http://codepad.org/iyrcdfQP

Here is a modification of that same slice of code that makes the href= a little more like what you are describing, although it doesn't really make sense to me.
# generate url
$url = '';
if($currentDepth == $depth) {
$url = " href=".$GLOBALS['area_name']."=".$GLOBALS['area']."&$label=$key";
}
else {
$GLOBALS['area'] = $key;
$GLOBALS['area_name'] = $label;
}

I don't see why one would bother with recursoin and multiple dimensions in a world of 2 dimensions as the menu in a web page is!
I would go for 2 dimensions only, the first dimension is to keep all elements (without any criteria) and the second to keep infos about the element:
Check an example for yourself, you set which element to get the function displays it along with all ancestors and root elements of previous levels (as California is).
<?php
function buildMenuWalk($element,$menuElements)
{
for($i=0;$i<=$element;$i++)
{
//for a new level go to the next line
if(!isset($menuElements[$i]['ancestors']))
{
echo '<br>______________________________________</br>';
echo '<strong>',$menuElements[$i]['label'],'</strong> | ';
}
//if the element is reached display it along with ancestors
if($i==$element)
{
//echo all the ancestores
foreach($menuElements[$element]['ancestors'] as $value)
{
echo $menuElements[$value]['label'],' | ';
}
//display the element itself
echo '<font color=red>',$menuElements[$element]['label'],' | </font>';
}
}
}
//California
$menuElements[0]=Array('url'=>'http://www.California.com','label'=>'California');
$menuElements[1]=Array('url'=>'http://www.San Diego.com','label'=>'San Diego','ancestors'=>Array(0));
$menuElements[2]=Array('url'=>'http://www.San Jose.com','label'=>'San Jose','ancestors'=>Array(0,1));
$menuElements[3]=Array('url'=>'http://www.San Francisco.com','label'=>'San Francisco','ancestors'=>Array(0,1,2));
$menuElements[4]=Array('url'=>'http://www.Fresno.com','label'=>'San Francisco','ancestors'=>Array(0,1,2,3));
$menuElements[5]=Array('url'=>'http://www.Sacramento.com','label'=>'Sacramento','ancestors'=>Array(0,1,2,3,4));
//Wyoming
$menuElements[6]=Array('url'=>'http://www.Wyoming.com','label'=>'Wyoming');
$menuElements[7]=Array('url'=>'http://www.Cheyenne.com','label'=>'Cheyenne','ancestors'=>Array(6));
$menuElements[8]=Array('url'=>'http://www.Casper.com','label'=>'Casper','ancestors'=>Array(6,7));
$menuElements[9]=Array('url'=>'http://www.Laramie.com','label'=>'Laramie','ancestors'=>Array(6,7,8));
$menuElements[10]=Array('url'=>'http://www.Gillette.com','label'=>'Gillette','ancestors'=>Array(6,7,8,9));
$menuElements[11]=Array('url'=>'http://www.Rock Springs.com','label'=>'Rock Springs','ancestors'=>Array(6,7,8,9,10));
echo '<pre>';
buildMenuWalk(9,$menuElements);
?>

Since this function is recursively calling itself, you'll have to refer to a global variable to keep track of the previous tree. So here is the code that'll do what I think you want it to do. All of you have to change is the #generate url section.
# generate url
$url = '';
if($currentDepth == $depth) {
$url = " href=area=" . $GLOBALS['area'] . "&block=$key";
} else {
$GLOBALS['area'] = $key;
}

Related

Variable Anchor tags inside a variable post Wordpress

i have a very long article created by a user in Wordpress , i want to show a navigation on every article page with links to the titles of the current article.
e.g:
<h1 id='title1'>Title 1</h1>
bla bla bla
<h1 id='title2'>Title 2</h1>
bla bla
my navigation on this page would be Anchor link to title 1
The example above is how you would hardcode it, but my article text is obviously variable and so are my links, what is the best way to tackle this with php?
Edit: the situation is not exactly like the example, the user puts text into a wordpress text editor field and doesnt want to write html tags, so the navigation needs to be filled with the titles that the user has put in the text field and those link to the variable titles on the page. (with an anchor i assume)
the functionality would be something like Microsoft word:
You can filter the content in order to target the different titles, add an ID in a form of a slug using sanitize_title on each of them and build a hierarchical array of those titles in order to display the anchor menu on top of the post.
I just wrote this filter for the example, but it is totally not tested so you may have to debug it a bit and change it depending of your needs. Please note that it works for a 3 level hierarchy maximum.
function add_anchor_menu($content) {
// First you may want to do some check here to see if this filter should be trigger on the current post...
$arrayTitles = array();
// Generate the ids...
$content = preg_replace_callback(
'#<h([1-3])>(.*?)<\/h[1-3]>#',
function($matches) {
$id = sanitize_title($matches[2]);
$meta = array('id' => $id, 'title' => $matches[2], 'childs' => array());
if((int)$matches[1] == 1) {
array_push($arrayTitles, $meta);
} elseif((int)$matches[1] == 2) {
end($arrayTitles);
array_push($arrayTitles[key($arrayTitles)]['childs'], $meta);
} else {
end($arrayTitles);
end($arrayTitles[key($arrayTitles)]['childs']);
array_push($arrayTitles[key($arrayTitles)]['childs'][key($arrayTitles[key($arrayTitles)])], $meta);
}
return '<h' . $matches[1] . ' id="' . $id . '">' . $matches[2] . '</h' . $matches[1] . '>';
},
$content
);
// And generate the menu...
if(count($arrayTitles) > 0) {
$menu = '<ul id="anchor-menu">';
foreach($arrayTitles as $level1) {
$menu .= '<li>';
$menu .= '' . $level1['title'] . '';
if(count($level1['childs']) > 0) {
$menu .= '<ul>';
foreach($level1['childs'] as $level2) {
$menu .= '<li>';
$menu .= '' . $level2['title'] . '';
if(count($level2['childs']) > 0) {
$menu .= '<ul>';
foreach($level2['childs'] as $level3) {
$menu .= '<li>' . $level3['title'] . '</li>';
}
$menu .= '</ul>';
}
$menu .= '</li>';
}
$menu .= '</ul>';
}
$menu .= '</li>';
}
$menu .= '<ul>';
$content = $menu . $content;
}
return $content;
}
add_filter('the_content', 'add_anchor_menu');
In your mark up
<h1 id="<?php echo get_the_title(); ?>">Title 1</h1>
Anchor link to title 1
You should esc_url() in the href attribute as well.

Creating a table of contents in php

I am looking to create a very simple, very basic nested table of contents in php which gets all the h1-6 and indents things appropriately. This means that if I have something like:
<h1>content</h1>
<h2>more content</h2>
I should get:
content
more content.
I know it will be css that creates the indents, that's fine, but how do I create a table of contents with working links to the content on the page?
apparently its hard to grasp what I am asking for...
I am asking for a function that reads an html document and pulls out all the h1-6 and makes a table of contents.
I used this package, it's pretty easy and straight forward to use.
https://github.com/caseyamcl/toc
Install via Composer by including the following in your composer.json file:
{
"require": {
"caseyamcl/toc": "^3.0",
}
}
Or, drop the src folder into your application and use a PSR-4 autoloader to include the files.
Usage
This package contains two main classes:
TOC\MarkupFixer: Adds id anchor attributes to any H1...H6 tags that do not already have any (you can specify which header tag levels to use at runtime)
TOC\TocGenerator: Generates a Table of Contents from HTML markup
Basic Example:
$myHtmlContent = <<<END
<h1>This is a header tag with no anchor id</h1>
<p>Lorum ipsum doler sit amet</p>
<h2 id='foo'>This is a header tag with an anchor id</h2>
<p>Stuff here</p>
<h3 id='bar'>This is a header tag with an anchor id</h3>
END;
$markupFixer = new TOC\MarkupFixer();
$tocGenerator = new TOC\TocGenerator();
// This ensures that all header tags have `id` attributes so they can be used as anchor links
$htmlOut = "<div class='content'>" . $markupFixer->fix($myHtmlContent) . "</div>";
//This generates the Table of Contents in HTML
$htmlOut .= "<div class='toc'>" . $tocGenerator->getHtmlMenu($myHtmlContent) . "</div>";
echo $htmlOut;
This produces the following output:
<div class='content'>
<h1 id="this-is-a-header-tag-with-no-anchor-id">This is a header tag with no anchor id</h1>
<p>Lorum ipsum doler sit amet</p>
<h2 id="foo">This is a header tag with an anchor id</h2>
<p>Stuff here</p>
<h3 id="bar">This is a header tag with an anchor id</h3>
</div>
<div class='toc'>
<ul>
<li class="first last">
<span></span>
<ul class="menu_level_1">
<li class="first last">
This is a header tag with an anchor id
<ul class="menu_level_2">
<li class="first last">
This is a header tag with an anchor id
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
For this you have just to search for the tags in the HTML code.
I wrote two functions (PHP 5.4.x).
The first one returns an array, that contains the data of the table of contents. The data is is only the headline it self, the id of the tag (if you want to use anchors) and a sub-table of content.
function get_headlines($html, $depth = 1)
{
if($depth > 7)
return [];
$headlines = explode('<h' . $depth, $html);
unset($headlines[0]); // contains only text before the first headline
if(count($headlines) == 0)
return [];
$toc = []; // will contain the (sub-) toc
foreach($headlines as $headline)
{
list($hl_info, $temp) = explode('>', $headline, 2);
// $hl_info contains attributes of <hi ... > like the id.
list($hl_text, $sub_content) = explode('</h' . $depth . '>', $temp, 2);
// $hl contains the headline
// $sub_content contains maybe other <hi>-tags
$id = '';
if(strlen($hl_info) > 0 && ($id_tag_pos = stripos($hl_info,'id')) !== false)
{
$id_start_pos = stripos($hl_info, '"', $id_tag_pos);
$id_end_pos = stripos($hl_info, '"', $id_start_pos);
$id = substr($hl_info, $id_start_pos, $id_end_pos-$id_start_pos);
}
$toc[] = [ 'id' => $id,
'text' => $hl_text,
'sub_toc' => get_headlines($sub_content, $depth + 1)
];
}
return $toc;
}
The second returns a string that formats the toc with HTML.
function print_toc($toc, $link_to_htmlpage = '', $depth = 1)
{
if(count($toc) == 0)
return '';
$toc_str = '';
if($depth == 1)
$toc_str .= '<h1>Table of Content</h1>';
foreach($toc as $headline)
{
$toc_str .= '<p class="headline' . $depth . '">';
if($headline['id'] != '')
$toc_str .= '<a href="' . $link_to_htmlpage . '#' . $headline['id'] . '">';
$toc_str .= $headline['text'];
$toc_str .= ($headline['id'] != '') ? '</a>' : '';
$toc_str .= '</p>';
$toc_str .= print_toc($headline['sub_toc'], $link_to_htmlpage, $depth+1);
}
return $toc_str;
}
Both functions are far away from being perfect, but they work fine in my tests. Feel free to improve them.
Notice: get_headlines is not a parser, so it does not work on broken HTML code and just crashes. It also only works with lowercase <hi>-tags.
How about this (although it can only do one H level) ...
function getTOC(string $html, int $level=1) {
$toc="";
$x=0;
$n=0;
$html1="";
$safety=1000;
while ( $x>-1 and $safety-->0 ) {
$html0=strtolower($html);
$x=strpos($html0, "<h$level");
if ( $x>-1 ) {
$y=strpos($html0, "</h$level>");
$part=strip_tags(substr($html, $x, $y-$x));
$toc .="<a href='#head$n'>$part</a>\n";
$html1.=substr($html,0,$x)."<a name='head$n'></a>".substr($html, $x, $y-$x+5)."\n";
$html=substr($html, $y+5);
$n++;
}
}
$html1.=$html;
$html=$toc."\n<HR>\n".$html1;
return $html;
}
This will create a basic list of links
$html="<html><body>";
$html.="<h1>Heading 1a</h1>One Two Three";
$html.="<h2>heading 2a</h2>Four Five Six";
$html.="<h1 class='something'>Heading 1b</h1>Seven Eight Nine";
$html.="<h2>heading 2b</h2>Ten Eleven Twelve";
$html.="</body></html>";
echo getTOC($html, 1);
gives...
<a href='#head0'>Heading 1a</a>
<a href='#head1'>Heading 1b</a>
<HR>
<html><body><a name='head0'></a><h1>Heading 1a</h1>
One Two Three<h2>heading 2a</h2>Four Five Six<a name='head1'></a><h1
class='something'>Heading 1b</h1>
Seven Eight Nine<h2>heading 2b</h2>Ten Eleven Twelve</body></html>
See https://onlinephp.io/c/fceb0 for a running example
This function return the string with appended table of content only for h2 tags. 100% tested code.
function toc($str){
$html = preg_replace('/]+\>/i', '$0 In This Article', $str, 1); //toc just after first image in content
$doc = new DOMDocument();
$doc->loadHTML($html);
// create document fragment
$frag = $doc->createDocumentFragment();
// create initial list
$frag->appendChild($doc->createElement('ul'));
$head = &$frag->firstChild;
$xpath = new DOMXPath($doc);
$last = 1;
// get all H1, H2, …, H6 elements
$tagChek = array();
foreach ($xpath->query('//*[self::h2]') as $headline) {
// get level of current headline
sscanf($headline->tagName, 'h%u', $curr);
array_push($tagChek,$headline->tagName);
// move head reference if necessary
if ($curr parentNode->parentNode;
}
} elseif ($curr > $last && $head->lastChild) {
// move downwards and create new lists
for ($i=$last; $ilastChild->appendChild($doc->createElement('ul'));
$head = &$head->lastChild->lastChild;
}
}
$last = $curr;
// add list item
$li = $doc->createElement('li');
$head->appendChild($li);
$a = $doc->createElement('a', $headline->textContent);
$head->lastChild->appendChild($a);
// build ID
$levels = array();
$tmp = &$head;
// walk subtree up to fragment root node of this subtree
while (!is_null($tmp) && $tmp != $frag) {
$levels[] = $tmp->childNodes->length;
$tmp = &$tmp->parentNode->parentNode;
}
$id = 'sect'.implode('.', array_reverse($levels));
// set destination
$a->setAttribute('href', '#'.$id);
// add anchor to headline
$a = $doc->createElement('a');
$a->setAttribute('name', $id);
$a->setAttribute('id', $id);
$headline->insertBefore($a, $headline->firstChild);
}
// echo $frag;
// append fragment to document
if(!empty($tagChek)):
$doc->getElementsByTagName('section')->item(0)->appendChild($frag);
return $doc->saveHTML();
else:
return $str;
endif;
}

PHP force reset counter to 0

I have a counter of menu items, that basically add incremental value as a class to a menu system:
<?php
if ($element['#original_link']['depth'] == 1) {
static $counter = 0;
$counter++;
$class = 'count-' . $counter;
}
$output = 'some output code build';
return '<li class="' . $class . '">' .$output .'</li>';
?>
Note, the code is inside each menu item (outside a loop or array). The code will simply output the lists of unordered list, without UL:
<li class="count-1">One</li>
<li class="count-2">Two</li>, ...etc.
This works fine until I change the source of menus.
1). One is using the system menu of my CMS,
2). the latter is using a block output of that system menu,
and both output similar construct of menus, except for the fact that the latter continues the counter from the #1 rather than a reset from a 1 (although #1 is not activated once #2 takes over the place). I haven't figured out why, but it seems that #2 is a continuance of #1. While I expect each should start an increment from 1.
I can not use a reset here. Is there anything obvious I missed that PHP can handle here, apart from the the way of my CMS do to the counters?
Any pointer would be very much appreciated. Thanks
UPDATE, actual codes in use:
function mytheme_menu_link(array $variables) {
//dpm($variables);
$element = $variables['element'];
$sub_menu = '';
if ($element['#below']) {
$sub_menu = drupal_render($element['#below']);
}
if ($element['#original_link']['menu_name'] == variable_get('menu_main_links_source', 'main-menu')) {
if ($element['#original_link']['depth'] == 1) {
static $counter = 0;
$counter++;
$element['#attributes']['class'][] = 'count-' . $counter;
}
}
$output = l($element['#title'], $element['#href'], $element['#localized_options']);
return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}
/**
* Implements theme_menu_tree()
No helpful variables, except for a flattened render of tree
*/
function mytheme_menu_tree__main_menu($variables) {
return '<ul class="menu">' . $variables['tree'] . '</ul>';
}
When using static variables, the values of the variable will not be reset between subsequent executions of the same code. That's the express purpose of static. Get rid of it if you do not want that behavior.

How to increment $var value without a loop in PHP?

I have this issue where i want to increase a value with 1 and apply this to my HTML, but i can't use a for() or while() loop (at least i think i can't). I'm customizing an e-merchandise program (opencart) and my php knowledge isn't enough to tackle the problem.
There is this function which displays the categories from the store. It uses a variable that is constantly updated via $var .= "value".
I'm so far that i know how many sub-categories there are, but i don't know how to apply this range to my HTML.
I'm working towards a situation like below
<ul id="cats">
<li id="cat1">Cat
<ul id="sub1">
<li>item</li>
<li>item</li>
</ul>
</li>
<li id="cat2">Cat
<ul id="sub2">
<li>item</li>
<li>item</li>
</ul>
</li>
</ul>
I don't have a clue how to increase the count of the second unordered lists. Below the code where the second unordered lists are generated.
[..]
$cPiD = strlen($parent_id);
if ($results) {
if ($parent_id == 0) {
$output .= '<ul id="cats">';
} else {
$output .= '<ul id="sub'.$cPiD.'">';
}
}
[..]
The variable $cPiD holds the total amount of sub categories (in this case 2). I want this variable to automatically apply the correct number to the unordered list (so apply id="sub1" to the first unordered list and id="sub2" tot he second one (as in my example above)).
The problem is that i can't use a for() loop after the else part, because in my HTML i wil get two <ul> tags instead of one.
Below the PHP code where it all happens
$category_id = array_shift($this->path);
$output = '';
$results = $this->model_catalog_category->getCategories($parent_id);
$count = 0;
$cPiD = strlen($parent_id);
if ($results) {
if ($parent_id == 0) {
$output .= '<ul id="cats">';
} else {
$output .= '<ul id="sub'.$cPiD.'">';
}
}
foreach ($results as $result) {
$count++;
if (!$current_path) {
$new_path = $result['category_id'];
$output .= '<li id="cat'.$count.'">';
} else {
$new_path = $current_path . '_' . $result['category_id'];
$output .= '<li>';
}
$children = '';
$children = $this->getCategories($result['category_id'], $new_path);
$output .= $result['name'];
$output .= $children;
if (!$current_path) {
$output .= '</li>';
} else {
$output .= '</li>';
}
}
if ($results) {
if ($parent_id == 0) {
$output .= '</ul>';
} else {
$output .= '</ul>';
}
}
Does anybody maybe have an idea how to solve this?
EDIT:
Oh, i tries adding the following construction in the foreach() loop, but that gave problems when a certain categories don't have any sub categories.
if (!$current_path) {
$output .= '$result['name'] . ' <ul id="sub'.$count.'">';
}else{
$output .= $result['name'];
}
You can use this:
// at the top of your code (ouside of the loop)
$cPiD = 1;
// inside the loop you need to increment the parameter
$output .= '<ul id="sub'.$cPiD++.'">';
After each time the item is used, its value will be incremented by 1. (after already using it)

Drupal Adding Span inside A tags in Nice Menus

I am trying to add drop down menus to a drupal theme which uses text sliding door CSS rounding.
The current version uses a primary links injection of the span into the a tags, which works fine. But doesn't support drop down menus.
Working code:
<?php print theme('links', $primary_links, array('class' => 'links primary-links')) ?>
In the template with a template.php file addition:
<?php
// function for injecting spans inside anchors which we need for the theme's rounded corner background images
function strands_guybrush_links($links, $attributes = array('class' => 'links')) {
$output = '';
if (count($links) > 0) {
$output = '<ul'. drupal_attributes($attributes) .'>';
$num_links = count($links);
$i = 1;
foreach ($links as $key => $link) {
$class = $key;
// Add first, last and active classes to the list of links to help out themers.
if ($i == 1) {
$class .= ' first';
}
if ($i == $num_links) {
$class .= ' last';
}
if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))) {
$class .= ' active';
}
$output .= '<li'. drupal_attributes(array('class' => $class)) .'>';
if (isset($link['href'])) {
$link['title'] = '<span class="link">' . check_plain($link['title']) . '</span>';
$link['html'] = TRUE;
// Pass in $link as $options, they share the same keys.
$output .= l($link['title'], $link['href'], $link);
}
else if (!empty($link['title'])) {
// Some links are actually not links, but we wrap these in <span> for adding title and class attributes
if (empty($link['html'])) {
$link['title'] = check_plain($link['title']);
}
$span_attributes = '';
if (isset($link['attributes'])) {
$span_attributes = drupal_attributes($link['attributes']);
}
$output .= '<span'. $span_attributes .'>'. $link['title'] .'</span>';
}
$i++;
$output .= "</li>\n";
}
$output .= '</ul>';
}
return $output;
}
?>
So I have added the Nice Menu module which works well and allows the drop down menu functions for my navigation which is now addressed from the template using:
<?php print theme_nice_menu_primary_links() ?>
The issue is that the a tags need to have spans inside to allow for the selected state markup. I have tried every angle I could find to edit the drupal function menu_item_link which is used by nice menus to build the links.
E.g. I looked at the drupal forum for two days and no joy.
The lines in the module that build the links are:
function theme_nice_menu_build($menu) {
$output = '';
// Find the active trail and pull out the menus ids.
menu_set_active_menu_name('primary-links');
$trail = menu_get_active_trail('primary-links');
foreach ($trail as $item) {
$trail_ids[] = $item['mlid'];
}
foreach ($menu as $menu_item) {
$mlid = $menu_item['link']['mlid'];
// Check to see if it is a visible menu item.
if ($menu_item['link']['hidden'] == 0) {
// Build class name based on menu path
// e.g. to give each menu item individual style.
// Strip funny symbols.
$clean_path = str_replace(array('http://', '<', '>', '&', '=', '?', ':'), '', $menu_item['link']['href']);
// Convert slashes to dashes.
$clean_path = str_replace('/', '-', $clean_path);
$class = 'menu-path-'. $clean_path;
$class .= in_array($mlid, $trail_ids) ? ' active' : '';
// If it has children build a nice little tree under it.
if ((!empty($menu_item['link']['has_children'])) && (!empty($menu_item['below']))) {
// Keep passing children into the function 'til we get them all.
$children = theme('nice_menu_build', $menu_item['below']);
// Set the class to parent only of children are displayed.
$class .= $children ? ' menuparent ' : '';
// Add an expanded class for items in the menu trail.
$output .= '<li id="menu-'. $mlid .'" class="'. $class .'">'. theme('menu_item_link', $menu_item['link']);
// Build the child UL only if children are displayed for the user.
if ($children) {
$output .= '<ul>';
$output .= $children;
$output .= "</ul>\n";
}
$output .= "</li>\n";
}
else {
$output .= '<li id="menu-'. $mlid .'" class="'. $class .'">'. theme('menu_item_link', $menu_item['link']) .'</li>'."\n";
}
}
}
return $output;
}
As you can see the $output uses menu_item_link to parse the array into links and to added the class of active to the selected navigation link.
The question is how do I add a span inside the a tags OR how do I wrap the a tags with a span that has the active class to style the sliding door links?
If you want to wrap the a tags with a span, you can overwrite the theme_nice_menu_build and add your span to the output. If you want to inside the a tag you need to overwrite the menu_item_link.
You can overwrite a theme funciton by creation a function call your_theme_name_function_name and Drupal will use that function to render the markup instead of the default one. That way you can alter the markup any way you want. This function should be in your theme's template.php file.
A good way to start is to copy the function you want to overwrite and just alter to your likings.
A lot has happened since Drupal 4.7, I don't hope you use that. It's quite easy to insert span tags:
function your_theme_name_menu_item_link($link) {
if (empty($link['localized_options'])) {
$link['localized_options'] = array();
}
$link['localized_options']['html'] = TRUE;
return l('<span>' . $link['title'] . '</span>', $link['href'], $link['localized_options']);
}
I tested this and it works just fine.

Categories