Get post ID from the Create post/page admin interface?

I am adding a meta box in the create post/page interface and I want to get the ID of the post being edited/created so I can dynamically display the value of the input field.

From the WordPress codex :

Read More
/* Prints the box content */
function myplugin_inner_custom_box() {

  // Use nonce for verification
  wp_nonce_field( plugin_basename(__FILE__), 'myplugin_noncename' );

  // The actual fields for data entry
  echo '<label for="myplugin_new_field">' . __("Description for this field", 'myplugin_textdomain' ) . '</label> ';
  echo '<input type="text" id= "myplugin_new_field" name="myplugin_new_field" value="whatever" size="25" />';
}

How do I pass the ID to myplugin_inner_custom_box()? So I can use the following within it:

// Get the value of the meta key that is associated to the page
  $as_meta_value = get_post_meta( $post_id, 'as_link_to_image', true );

and replace the whatever value with the value of the meta key in the input field.

Related posts

Leave a Reply

2 comments

  1. Hi @Joann:

    When creating post admin metaboxes, the standard way to get the Post’s ID in a metabox is via a $post parameter in the callback function. The following is a subset of the code taken from the Codex found the same page you posted but after I updated it to remove 2 bugs:

    Hopefully this is self-explanitory?

    add_action('add_meta_boxes', 'myplugin_add_custom_box');
    function add_my_meta_box() {
      add_meta_box('metabox_id', 'Metabox Title', 'my_metabox_callback', 
          'page', 'normal', 'low');
    }
    function my_metabox_callback($post, $metabox) {
      echo get_post_meta($post->ID,'my_custom_field',true); 
    }