add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add($post)
{
$post_id = get_the_ID();
$parent_id = get_post($post_id)->post_parent;
if(!$parent_id){
add_meta_box( 'my-meta-box-id', 'Show this page in main menu', 'cd_meta_box_cb', 'page', 'side', 'high' );
}
}

function cd_meta_box_cb($post)
{

$values = get_post_custom( $post->ID );
//print_r($values);

$check = isset( $values['my_meta_box_check'] ) ? esc_attr( $values['my_meta_box_check'][0] ) : "";

?>
<br />
<input type="checkbox" name="my_meta_box_check" id="my_meta_box_check" value="1" <?php checked( $check, 1 ); ?> />
<label for="my_meta_box_text">Show this page in main navigation menu</label>
<br /><br />
<?php
}

add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $post_id )
{
$chk = isset( $_POST['my_meta_box_check'] ) ? $_POST['my_meta_box_check'] : 0;

if($chk)
$chk_prev=0;
else
$chk_prev=1;

update_post_meta( $post_id, 'my_meta_box_check', $chk, $chk_prev );
}

We need to put this code in our theme’s function.php or in our plugin’s file

I display the meta-box conditionally, if page has not any parent than it will display.

Advertisements