Mecha CMS

Mecha CMS blog and documentation.

Automatic Menu Navigation

Updated: Sunday, 07 August 2016

Automatically generates menu items.

Image

Mecha provides a hook that can be used to manipulate the input and output data on the menu. This allows you to insert data on a particular menu automatically.

// as array data
Filter::add('menu:input', function($array, $id) { … });
// as markup data
Filter::add('menu:output', function($html, $id) { … });

Automatic Tags Menu

Add this snippet to functions.php:

Filter::add('menu:input', function($array, $id) use($config) {
    // Insert to `Menu::navigation()` ...
    if($id === 'navigation') {
        // Build array of tags ...
        $tags = array();
        foreach(Get::tags() as $k => $v) {
            $tags[$v->name] = '/' . $config->tag->slug . '/' . $v->slug;
        }
        array_walk_recursive($array, function(&$v, $k) use($tags) {
            if($v === '{{this.tags}}') $v = $tags;
        });
    }
    return $array;
});

Then go to the menu manager page to create a new menu with the value of {{this.tags}}. Once saved, the shortcode pattern will be replaced by the tags data:

Home: /
About: /about
Tags: {{this.tags}}

Automatic Pages Menu

Add this snippet to functions.php:

Filter::add('menu:input', function($array, $id) use($config) {
    // Insert to `Menu::navigation()`
    if($id === 'navigation') {
        // Build array of pages ...
        $pages = array();
        foreach(Get::pages() as $page) {
            $page = Get::pageAnchor($page);
            $pages[$page->title] = $page->link ? $page->link : $page->url;
        }
        array_walk_recursive($array, function(&$v, $k) use($pages) {
            if($v === '{{this.pages}}') $v = $pages;
        });
    }
    return $array;
});

Then go to the menu manager page to create a new menu with the value of {{this.pages}}:

Home: /
About: /about
Tags: {{this.tags}}
Pages: {{this.pages}}

Related: Create Dynamic Menu from the Existing Pages

Donation and Email Subscription