6

I've variously seen register_nav_menus() called:

  • on after_setup_theme
  • on init
  • pasted "loose" into functions.php

with no apparent change in functionality.

Which hook should I be using to call this function?

3 Answers 3

6

First off, you should not register functions loose in functions.php because you cannot remove them (using remove_action). It can also cause debug errors since WP may not yet be stable. By using a hook you are making sure WP is stable enough to run your code, and what you need to use has been loaded.

Check out the answer on the Wordpress Forums for more info


To decide which hook to use, first check out this answer.

The main difference between the two:

  • The user is not authenticated at after_setup_theme
  • The user becomes authenticated at init.

The after_setup_theme hook is therefore obviously run before init, you can see this in the Action Reference

According to the Wordpress Codex page on after_setup_theme:

This hook is called during each page load, after the theme is initialized. It is generally used to perform basic setup, registration, and init actions for a theme.


Since you are registering menus, I would suggest using after_setup_theme. The Wordpress Codex for register_nav_menu() also uses the after_setup_theme hook in one of the examples.

2
  • 1
    ...there is really not much of a problem with registering it loosly in functions.php. Not true. You cannot remove these with a simple remove_action from a child theme or a plugin. NEVER do that Feb 11, 2016 at 12:32
  • I edited my answer, and added a link to a post on the Wordpress Forums discussing it
    – Kaspar Lee
    Feb 11, 2016 at 12:41
1

You can use them the moment they are available i.e. as soon as functions.php is loaded, hence why you've seen so many different options.

I would recommend sticking with the "defacto" way - using the hook after_setup_theme

1

The docs for register_nav_menu show an example using the after_setup_theme hook so I would use that.

after_setup_theme

This hook is called during each page load, after the theme is initialized. It is generally used to perform basic setup, registration, and init actions for a theme.

...the after_setup_theme hook, which runs before the init hook. The init hook is too late for some features, such as indicating support post thumbnails.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.