Read This Offline With Code With Me APP

Add Comment Metabox in WordPress

Posted On: Jun 16, 2015

If you like to add new metabox (custom field for wordpress comment like Phone, Address etc. then this tutorial will be helpful. The Wordpress has name, email, URL, and comment fields by default.
  •  Add following PHP code to functions.php
 


<?php
	//add metabox to comment

	// SAVE COMMENT META
	// only found this hook to process the P
	add_filter( 'comment_edit_redirect','save_comment_wpse_82317', 10, 2 );
	// META BOX
	add_action( 'add_meta_boxes','add_custom_box_wpse_82317' );
	/**
	 * Save Custom Comment Field
	 * This hook deals with the redirect aft saving, we are only taking advantage of i
	 */
	function save_comment_wpse_82317( $location,$comment_id )
	{
		// Not allowed, return regular value without updating meta
		if ( !wp_verify_nonce( $_POST['noncename_wpse_82317'], plugin_basename( __FILE__ ) ) && !isset( $_POST['meta_comment_field'] ))
			return $location;
		// Update meta
		update_comment_meta($comment_id,'comment_author_address',sanitize_text_field( $_POST['address'] ));
		update_comment_meta($comment_id,'comment_author_phone',sanitize_text_field( $_POST['phone'] ));
		// Return regular value after updatin
		return $location;
	}
	/**
	 * Add Comment meta box
	 */
	function add_custom_box_wpse_82317()
	{
		add_meta_box(
			 'section_id_wpse_82317',
			__( 'Other Details' ),
			'render_custom_box_wpse_82317',
			'comment',
			'normal'
		);
	}
	/**
	 * Render meta box with Custom Field
	 */
	function render_custom_box_wpse_82317( $comment )
	{
		//add_comment_meta($comment_id,'comment_author_address',$address);
		//add_comment_meta($comment_id,'comment_author_phone',$phone);
		// Use nonce for verification
		wp_nonce_field( plugin_basename( __FILE__ ), 'noncename_wpse_82317' );
		$address = get_comment_meta( $comment->comment_ID, 'comment_author_address', true );
		$phone = get_comment_meta( $comment->comment_ID, 'comment_author_phone', true );
		echo('<table width=100%>');
		echo "<tr><td>Address :</td><td><input type='text'id='address' name='address' value='".esc_attr( $address )."' size='25' /></td></tr>";
		echo "<tr><td>Phone :</td><td><input type='text'id='phone' name='phone' value='".esc_attr( $phone )."' size='25' /></td></tr>";
		echo('</table>');
	}


?>

Tags:

  • metabox
  • php
  • wordpress

Share This On

Comments