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?)

2 s
2

Have a look at this list: http://codex.wordpress.org/Plugin_API/Action_Reference

  1. It doesn’t matter which one you use as long as it’s not too early and not too late. It’s best to use intuitive and predictable hooks, so 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.
  2. There is one exception that I can think of to that. Sometimes (in cases that are very unlikely to happen) you may need to for instance call add_theme_support() which is generally used with after_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 use set_current_user or init action hooks instead (after doing some research if it’s safe to do that).

Leave a Reply

Your email address will not be published. Required fields are marked *