When setting up meta boxes in a custom post type I’ve been do so using the add_meta_boxes
hook, e.g.
add_action('add_meta_boxes', 'meta_box_setup');
function meta_box_setup()
{
add_meta_box(
'mb_movie_review',
'Movie Review Details',
'display_movie_review_mb',
'movie-reviews',
'side',
'high'
);
}
But I’ve just read this tutorial which does the following using the admin_init
hook, like so…
add_action('admin_init', 'meta_box_setup');
function meta_box_setup()
{
add_meta_box(
'mb_movie_review',
'Movie Review Details',
'display_movie_review_mb',
'movie-reviews',
'side',
'high'
);
}
This is the first time I’ve seen it done using the admin_init
hook.
Question
The latter method (using admin_init
) does work but …
- is this the preferred method? (i.e. more optimized?)
- just a different way of achieving the same results, or
- a bad way to add meta boxes? (if so, why?)
Have a look at this list: http://codex.wordpress.org/Plugin_API/Action_Reference
add_meta_boxes
is preferred. Someday in the future WordPress may change something and by using the most appropriate hooks you increase your chances that your code will still work in the future.add_theme_support()
which is generally used withafter_setup_theme
action hook only for logged in users that are administrators but this hook doesn’t allow you to access this information yet. You would therefore have to probably useset_current_user
orinit
action hooks instead (after doing some research if it’s safe to do that).There are several other hooks:
and immediately afterwards runs:
If you want to perform different abort checks from within the hook/callback that actually registers the meta boxes, use one of the above as the
WP_Screen
object isn’t filled as early asadmin_init
runs.If you used the more generic
add_meta_boxes
hook, you can check against its first argument:If you don’t want to add your meta box as long as the post hasn’t been saved at least once, you could check
and so on. Conclusion: If you want to narrow things down, use the hooks shown above.