我在Wordpress中构建了一个自定义菜单,其中包含指向帖子和页面的链接。我使用以下代码行将其添加到标题中:
<?php
wp_nav_menu(
array(
\'theme_location\' => \'primary\',
\'depth\' => 0,
\'menu_class\' => \'nav-menu\',
)
);
?>
我的问题是,如果我将子页面添加到菜单的顶层页面,它们不会自动在nav上显示为子链接。我知道每次都可以通过重建菜单手动创建它们,但我希望能够在页面部分添加一个子页面,并将其显示在导航中,而无需转到菜单并在那里构建它,如果这有意义的话?
我试过使用depth => 0
, 但那没用。有没有一种方法可以显示子页面,而不必将其构建到自定义菜单中?
最合适的回答,由SO网友:Bainternet 整理而成
here is how:
/**
* auto_child_page_menu
*
* class to add top level page menu items all child pages on the fly
* @author Ohad Raz <[email protected]>
*/
class auto_child_page_menu
{
/**
* class constructor
* @author Ohad Raz <[email protected]>
* @param array $args
* @return void
*/
function __construct($args = array()){
add_filter(\'wp_nav_menu_objects\',array($this,\'on_the_fly\'));
}
/**
* the magic function that adds the child pages
* @author Ohad Raz <[email protected]>
* @param array $items
* @return array
*/
function on_the_fly($items) {
global $post;
$tmp = array();
foreach ($items as $key => $i) {
$tmp[] = $i;
//if not page move on
if ($i->object != \'page\'){
continue;
}
$page = get_post($i->object_id);
//if not parent page move on
if (!isset($page->post_parent) || $page->post_parent != 0) {
continue;
}
$children = get_pages( array(\'child_of\' => $i->object_id) );
foreach ((array)$children as $c) {
//set parent menu
$c->menu_item_parent = $i->ID;
$c->object_id = $c->ID;
$c->object = \'page\';
$c->type = \'post_type\';
$c->type_label = \'Page\';
$c->url = get_permalink( $c->ID);
$c->title = $c->post_title;
$c->target = \'\';
$c->attr_title = \'\';
$c->description = \'\';
$c->classes = array(\'\',\'menu-item\',\'menu-item-type-post_type\',\'menu-item-object-page\');
$c->xfn = \'\';
$c->current = ($post->ID == $c->ID)? true: false;
$c->current_item_ancestor = ($post->ID == $c->post_parent)? true: false; //probbably not right
$c->current_item_parent = ($post->ID == $c->post_parent)? true: false;
$tmp[] = $c;
}
}
return $tmp;
}
}
new auto_child_page_menu();