Archive pages in menus plugin – 01

I’ve run into the need to add archive pages to WordPress navigation menus and since a quick Google search yielded what I see as workarounds I’d like to try and come up with a solution.

Not user-friendly
Not user-friendly

While adding custom links containing search queries and RESTful URLs does work I find that solution too far from the user-friendly UI and interface WordPress offers.
While linking to the /events URL is not difficult the same cannot be done with the built-in and default post type: /posts.

Hooks please

I’ve run some XDebug sessions and dumped output here and there and found out that the screen to publish the meta box markup on is the nav-menus one.
Hooking into the traditional add_meta_boxes hook to add the meta box will actually lead nowhere: a quick action hook list check will reveal the hook is never fired on said screen.
What’s fired is, instead, the load-nav-menus.php hook and looking into WordPress source code will tell me that’s the place the magic is happening.

Hook list
Here it is

Just print something

First step is making sure I can:

  • hook properly
  • print something to the page

and after quickly scaffolding a new plugin using my faithful grunt-init plugin template (original template by 10up on GitHub) I will hook right there to actually print something

class Main
{
    public function __construct()
    {
        add_action('init', array($this, 'init'));
    }

    /*
     * Default initialization for the plugin:
     * - Registers the default textdomain.
     * - Hooks to add the render the archives meta box on nav menus screen.
    */
    public function init()
    {
        $locale = apply_filters('plugin_locale', get_locale(), 'navmenuarchives');
        load_textdomain('navmenuarchives', WP_LANG_DIR . '/navmenuarchives/navmenuarchives-' . $locale . '.mo');
        load_plugin_textdomain('navmenuarchives', false, dirname(plugin_basename(__FILE__)) . '/languages/');

        $this->hookToRenderArchivesMetabox();
    }

    public function hookToRenderArchivesMetabox()
    {
        $self = $this;
        add_action('load-nav-menus.php', function () 
        use ($self)
        {
            global $wp_meta_boxes;
            add_meta_box('archives', __('Archives', 'navmenuarchives'), array($self, 'theArchiveMetabox'), 'nav-menus', 'side');
        });
    }

    public function theArchiveMetabox($tax)
    {
        var_dump('hello there');
    }
}

and that will add the actually un-useful meta box to the list.

Var dump to nav menu
Hello there

Next step will be to put something in the meta box and make those archives available to the user for adding to navigation menus.

One thought on “Archive pages in menus plugin – 01

  1. So that’s how the ‘load-nav-menus.php’ hook works!
    This was just what I needed to get started. Thanks for the useful post!

    Looking forward for – 02! 😉

I appreciate your input