Do you mean that define the meta box for a specific page? If so, yes, it can be done. But before creating a demo, I want to ask more:
– how do you know that page in admin?
– by which criteria?
I need a way to define metaboxes page by page. Whether that be by ID or page title.
For example, the homepage, we usually have various content blocks on the homepage that we havent found a good way to put into the cms. We’d like to be able to define meta boxes and meta fields just for the homepage.
Likewise, we sometimes have meta boxes that we want on interior pages that we dont want on the homepage.
You can use this technique:
add_action( 'admin_init', 'prefix_register_meta_boxes' );
function prefix_register_meta_boxes()
{
global $post;
if ( ! class_exists( 'RW_Meta_Box' )
return;
if ( 123 != $post->ID )
return;
$meta_boxes = array();
$meta_boxes[] = ...;
foreach ( $meta_boxes as $meta_box )
{
new RW_Meta_Box( $meta_box );
}
}
I tried this, and had tried a variation of it before, and it doesnt work. Doesnt look like the $post info is available. Any other ideas?
You’re right. $post
is not available in admin_init
hook. Maybe you can try with admin_menu
.
No dice.
I was able to do it by getting the post id from the URL. However, it wouldnt save any of the meta.
Maybe this help:
add_action('admin_init','my_meta_init');
function my_meta_init()
{
if ( ! class_exists( 'RW_Meta_Box' )
return;
$post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ;
// checks for post/page ID
if ($post_id == '84')
{
$meta_boxes = array();
$meta_boxes[] = ...;
foreach ( $meta_boxes as $meta_box )
{
new RW_Meta_Box( $meta_box );
}
}
}
Okay, got it save the file but now it wont delete the file. It will delete just fine if I dont put the meta box in an if statement.
Thanks for your help with this.
If you don’t want to put the meta box in the if
statement (just to keep the code clean and avoid errors), you can put it outside the function, and use global $meta_boxes
.
Checkout the demo folder. There’s a new demo for including meta boxes for specific posts.