我已经为多级wordpress菜单编写了一个函数,但我希望它可以在任何级别上工作,目前它被编写为3级工作。
//only gets the top level items
$top_level_pages = get_pages('parent=0&sort_column=menu_order&exclude=129,2,13');
foreach($top_level_pages as $page){
//print_r($top_level_pages);
$p_id = $page->ID;
// gets all pages and subpages in one array
$children = get_pages("child_of=$p_id&sort_column=menu_order");
$immediate_children = get_pages("child_of=$p_id&parent=$p_id&sort_column=menu_order");
//print_r($immediate_children);
if($children) {
print '<li class="page_item page-item-'.$page->ID.'"><span class="first-level">'.$page->post_title;
print '</span><ul>';
foreach($immediate_children as $child){
$c_id = $child->ID;
//gets a preformatted menu
$grandchildren = wp_list_pages('depth=1&echo=0&parent='.$c_id.'&sort_column=menu_order&title_li=');
if($grandchildren) {
print '<li class="page_item page-item-'.$child->ID.'"><span class="second-level">'.$child->post_title;
print '</span><ul>';
print $grandchildren;
print '</ul></li>';
}
else {
print '<li class="page_item page-item-'.$child->ID.'"><a href="'.get_page_link($child->ID).'">'.$child->post_title.'</a></li>';
}
}
print '</ul></li>';
}
else {
print '<li class="page_item page-item-'.$page->ID.'"><a href="'.get_page_link($page->ID).'">'.$page->post_title.'</a></li>';
}
}
答案 0 :(得分:4)
我们需要做的就是让你的函数递归,将大部分循环移动到递归函数中:
<?php
//only gets the top level items
$top_level_pages = get_pages('parent=0&sort_column=menu_order&exclude=129,2,13');
foreach($top_level_pages as $page) {
//print_r($top_level_pages);
$p_id = $page->ID;
recursiveFunction($p_id);
}
function recursiveFunction($p_id){
$children = get_pages("child_of=$p_id&sort_column=menu_order");
$immediate_children = get_pages("child_of=$p_id&parent=$p_id&sort_column=menu_order");
//print_r($immediate_children);
if($children) {
print '<li class="page_item page-item-'.$page->ID.'"><span class="first-level">'.$page->post_title;
print '</span><ul>';
foreach($immediate_children as $child) {
recursiveFunction($child->ID);
}
print '</ul></li>';
}
else {
print '<li class="page_item page-item-'.$page->ID.'"><a href="'.get_page_link($page->ID).'">'.$page->post_title.'</a></li>';
}
}
?>
困难的部分是使“第一级”,“第二级”的东西工作。我只是将它改为“level-1”,“level-2”等等。然后你可以从$x = 1;
开始并在每次递归调用函数时传递$x+1
。
答案 1 :(得分:1)
这样的事情应该可以解决问题(写在堆栈溢出文本框中并且未经测试)。
function listChildren($parentID, &$menu)
{
static $options = 'parent=0&sort_column=menu_order&exclude=129,2,13';
static $level = 1;
foreach(get_pages(sprintf('child_of=%d&%s', $parentID, $options ) as $page)
{
$menu .= sprintf('<li class="level-%d"><a href="%s">%s</a>',
$level
get_page_link($page->ID),
$page->post_title);
if ($page->hasChildrenOrWhateverWPUses())
{
$level ++;
$menu .= sprintf('<ul class="menu-level-%d">', $level);
listChildren($page->ID, $menu);
$menu .= '</ul>';
$level --;
}
$menu .="</li>"
}
}
用过:
$menu = '<ul class="menu-tree">';
listChildren($rootPageID, $menu);
$menu .= '</ul>';
echo $menu;