Add a custom option to a page in backend

To add a option box for a page or post, you need to use add_meta_boxes action.

 //Register Meta Box
 function register_meta_box() {
      add_meta_box(
          'meta-box-id',
          __( 'MetaBox Title', 'text-domain' ), 
          'meta_box_callback', 
          'post', 
          'advanced', 
          'high' 
     );
 }
 add_action( 'add_meta_boxes', 'register_meta_box');

  //Add field
  function meta_box_callback( $post_id ) {

 $output="<label for="title_field">". esc_html__('Title Field', 'text-domain') .'</label>';
 $title_field = get_post_meta( $post_id->ID, 'title_field', true );
 $output .= '<input type="text" name="title_field" id="title_field" class="title_field" value="'. esc_attr($title_field) .'" />';

     echo $output;
 }

// Save meta field
add_action('save_post', 'save_meta_field');

function save_meta_field($post_id){
      // Check nonce, sanitize field
      update_post_meta($post_id, 'title_field', $_POST['title_field']);
}

The add_meta_box() parameters must be set to fit your needs (advanced and ‘high’), and of course the field name and the screen(s) where your want the box to appears.

You will find more details about add_meta_boxes here

Hope it helps

Leave a Comment