如何按照页面顺序而不是字母顺序对使用Get_Pages()生成的子菜单进行排序?

时间:2016-02-18 作者:Jaime Lopes

我希望wordpress网站的顶部导航自动显示子页面。

我知道我可以编辑菜单并添加子页面,但我希望它们自动显示,并且在我更改或添加子页面时,菜单会更新。

我使用本文中的代码部分实现了这一点:Add child pages automatically to nav menu

除了一件事之外,它工作得很好。。。它按字母顺序列出子页面,而不是创建页面时选择的顺序。

我怎样才能让菜单按正确的顺序显示孩子们?

1 个回复
最合适的回答,由SO网友:Jaime Lopes 整理而成

这就是我最终实现这一目标的方式。

我将以下代码放入我的函数中。php(实际上是我的孩子主题的functions.php,以确保其不受更新的影响)由于@birgire.

/**
* auto_child_page_menu
* 
* class to add top level page menu items all child pages on the fly
* @author Ohad Raz <[email protected]>
* with a tweak by birgire <https://wordpress.stackexchange.com/users/26350/birgire>
*/
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( \'sort_column\' => \'menu_order\', \'child_of\' => $i->object_id) ); //fetching the child pages according to the order set on the page
        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; //probably not right
            $c->current_item_parent   = ($post->ID == $c->post_parent)? true: false;
            $tmp[] = $c;
        }
    }
    return $tmp;
}
}
new auto_child_page_menu();
谢谢大家的帮助。。。