This creates a custom meta box and the contents of the textarea field it contains are being saved as a comment to the post. Please note:
-
Built with code sample adapted from the Codex.
Relevant functions:add_meta_box
andwp_insert_comment
. -
I removed
comment_author_IP
andcomment_agent
from the insert comment arguments. Not sure of the consequences. -
Bug: duplicated comments.Post revisions they were, thanks to @Hameedullah Khan… -
Tested as a
mu-plugin
and inside the theme’sfunctions.php
add_action( 'add_meta_boxes', 'add_custom_box_wpse_81739' );
add_action( 'save_post', 'save_postdata_wpse_81739', 10, 2 );
/* Adds a box to the main column on the Post and Page edit screens */
function add_custom_box_wpse_81739()
{
add_meta_box(
'sectionid_wpse_81739',
__( 'Publish a Comment' ),
'inner_custom_box_wpse_81739',
'post'
);
}
/* Prints the box content */
function inner_custom_box_wpse_81739( $post )
{
// Use nonce for verification
wp_nonce_field( plugin_basename( __FILE__ ), 'noncename_wpse_81739' );
// The actual fields for data entry
// Use get_post_meta to retrieve an existing value from the database and use the value for the form
//$value = get_post_meta( $post->ID, $key = '_my_meta_value_key', $single = true );
echo '<label for="new_field_wpse_81739">';
_e( "Enter your comment:" );
echo '<br />';
echo '<textarea id="new_field_wpse_81739" name="new_field_wpse_81739" cols="80" rows="5"></textarea></label>';
}
/* When the post is saved, saves our custom data */
function save_postdata_wpse_81739( $post_id, $post_object )
{
// verify if this is an auto save routine.
// If it is our form has not been submitted, so we dont want to do anything
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// don't run the echo if the function is called for saving revision.
if ( 'revision' == $post_object->post_type )
return;
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['noncename_wpse_81739'], plugin_basename( __FILE__ ) ) )
return;
// Check permissions
if ( 'page' == $_POST['post_type'] )
{
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
// OK, we're authenticated: we need to find and save the data
//sanitize user input
$mydata = esc_textarea( $_POST['new_field_wpse_81739'] );
$time = current_time('mysql');
global $current_user;
get_currentuserinfo();
$data = array(
'comment_post_ID' => $post_id,
'comment_author' => $current_user->user_login,
'comment_author_email' => $current_user->user_email,
'comment_author_url' => 'http://',
'comment_content' => $mydata,
'comment_type' => '',
'comment_parent' => 0,
'user_id' => $current_user->ID,
'comment_date' => $time,
'comment_approved' => 1,
);
wp_insert_comment( $data );
}