Adding Custom Metabox Context/locations On WordPress Edit/Add New screen
If you have added a meta box for your plugin and theme you already know that WordPress suggest three contexts for adding meta boxes, 'normal', 'advanced', or 'side'.
In one of my plugins(MediaPress), I wanted to add a few meta boxes before the WordPress post editor and after the title. None of the above context solved my issue. There is a hook "edit_form_after_title" that you can hook to show content before the editor. The problem was I wanted metabox holder to allow users reorganize their metaboxes as they please.
Looking a little bit in detail, I found that while registering the meta boxes, WordPress does not check if they only belong to the suggested three. That simply means, you can go ahead and add your own custom metabox context( that acts as holder) and render it to the location you want.
Here is an example, showing a smiple metabox on the post edit screen before the editor.
Step 1 :- Create a custom Context & Let WordPress render any meta boxes attached to it
1 2 3 4 5 | function buddydev_create_new_metboax_context( $post ) { do_meta_boxes( null, 'custom-metabox-holder', $post ); } add_action( 'edit_form_after_title', 'buddydev_create_new_metboax_context' ); |
The above code asks WordPress to render the context 'custom-metabox-holder' in between the title & the editor. $post is the post currently being edited.
Step 2 :- Add Meta boxes to our custom context.
Go ahead and add as many meta boxes as you want to the new context. Here is a simple example that display a snippet of text. You can add multiple meta boxes and do whatever you want.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function buddydev_add_custom_meta_box() { add_meta_box( 'awesome_metabox_id', __( 'This Is Awesome', 'buddydev' ), 'buddydev_render_awesome_metabox', 'post', 'custom-metabox-holder' //Look what we have here, a new context ); } add_action( 'add_meta_boxes', 'buddydev_add_custom_meta_box' ); function buddydev_render_awesome_metabox( $post ) { ?> <div class="awesome-meta-admin"> <?php //show something here echo "Having fun!"; ?> </div> <?php } |
Here is a screenshot.
Don't just stop there, you can create meta box contexts for your plugin/theme's settings page and allow others to extend. That's all folks. Do metaboxing not kickboxing 🙂
Reference: You can read more about the add_meta_box on WordPress Codex.
Interesting! It's easy at first to notice that and sometimes I quickly assumed it wasn't possible.
By the way, Ray added the option recently on BP Core to add metaboxes in BuddyPress related pages (on the admin site, such as activity and so on). Maye you could cover that here on Buddydev in the future.
Keep up the good work man! =)