Latest Post

How To Add Custom Fields for Comment Form in WordPress

How To Add Custom Fields for Comment Form in WordPress


How To Add Custom Fields for Comment Form in WordPress

We are need to add for more field for comment form . we are add for "phone Number" field . this code this for create a text box for comment form.

1. Add field for comment form.

add_filter('comment_form_default_fields', 'custom_fields');
function custom_fields($fields) {

    $commenter = wp_get_current_commenter();
    $req = get_option( 'require_name_email' );
    $aria_req = ( $req ? " aria-required='true'" : ’ );

    $fields[ 'phone' ] = '<p class="comment-form-phone">'.
      '<label for="phone">' . __( 'Phone' ) . '</label>'.
      '<input id="phone" name="phone" type="text" size="30"  tabindex="4" /></p>';

  return $fields;
}


2.  Save the comment meta data along with comment.

add_action( 'comment_post', 'save_comment_meta_data' );
function save_comment_meta_data( $comment_id ) {
  if ( ( isset( $_POST['phone'] ) ) && ( $_POST['phone'] != ’) )
  $phone = wp_filter_nohtml_kses($_POST['phone']);
  add_comment_meta( $comment_id, 'phone', $phone );

}

How To Add Custom Fields for Comment Form in WordPress


3 Add an edit option to comment editing screen in admin panel

add_action( 'add_meta_boxes_comment', 'extend_comment_add_meta_box' );
function extend_comment_add_meta_box() {
    add_meta_box( 'title', __( 'Comment Metadata - Extend Comment' ), 'extend_comment_meta_box', 'comment', 'normal', 'high' );
}

function extend_comment_meta_box ( $comment ) {
    $phone = get_comment_meta( $comment->comment_ID, 'phone', true );
    $title = get_comment_meta( $comment->comment_ID, 'title', true );
    $rating = get_comment_meta( $comment->comment_ID, 'rating', true );
    wp_nonce_field( 'extend_comment_update', 'extend_comment_update', false );
    ?>
    <p>
        <label for="phone"><?php _e( 'Phone' ); ?></label>
        <input type="text" name="phone" value="<?php echo esc_attr( $phone ); ?>" class="widefat" />
    </p>
    <?php
}


5. Update comment meta data from comment editing screen  in admin panel

add_action( 'edit_comment', 'extend_comment_edit_metafields' );

function extend_comment_edit_metafields( $comment_id ) {
    if( ! isset( $_POST['extend_comment_update'] ) || ! wp_verify_nonce( $_POST['extend_comment_update'], 'extend_comment_update' ) ) return;

  if ( ( isset( $_POST['phone'] ) ) && ( $_POST['phone'] != ’) ) :
  $phone = wp_filter_nohtml_kses($_POST['phone']);
  update_comment_meta( $comment_id, 'phone', $phone );
  else :
  delete_comment_meta( $comment_id, 'phone');
  endif;

}


How To Add Custom Fields for Comment Form in WordPress

No comments