Support » Plugins » Hacks » Add a comment field

  • Resolved Taro


    Dear all,

    Im trying to ad a custom comment field that works the same as the “Message” field. I found all topics and tutorials. But my php skills are not realy updated.

    What did i add? I put ‘test’. This is how i now tryed to edit the comment-template.php

    function comment_form( $args = array(), $post_id = null ) {
    	if ( null === $post_id )
    		$post_id = get_the_ID();
    		$id = $post_id;
    	$commenter = wp_get_current_commenter();
    	$user = wp_get_current_user();
    	$user_identity = $user->exists() ? $user->display_name : '';
    	if ( ! isset( $args['format'] ) )
    		$args['format'] = current_theme_supports( 'html5', 'comment-form' ) ? 'html5' : 'xhtml';
    	$req      = get_option( 'require_name_email' );
    	$aria_req = ( $req ? " aria-required='true'" : '' );
    	$html5    = 'html5' === $args['format'];
    	$fields   =  array(
    		'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Name' ) . ( $req ? ' <span class="required">*</span>' : '' ) . '</label> ' .
    		            '<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' /></p>',
    		'email'  => '<p class="comment-form-email"><label for="email">' . __( 'Email' ) . ( $req ? ' <span class="required">*</span>' : '' ) . '</label> ' .
    		            '<input id="email" name="email" ' . ( $html5 ? 'type="email"' : 'type="text"' ) . ' value="' . esc_attr(  $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . ' /></p>',
    		'url'    => '<p class="comment-form-url"><label for="url">' . __( 'Website' ) . '</label> ' .
    		            '<input id="url" name="url" ' . ( $html5 ? 'type="url"' : 'type="text"' ) . ' value="' . esc_attr( $commenter['comment_author_url'] ) . '" size="30" /></p>',
    	$required_text = sprintf( ' ' . __('Required fields are marked %s'), '<span class="required">*</span>' );
    	$defaults = array(
    		'fields'               => apply_filters( 'comment_form_default_fields', $fields ),
    		'comment_field'        => '<p class="comment-form-comment"><label for="comment">' . _x( 'Comment', 'noun' ) . '</label> <textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea></p>',
    		'test'			=> '<p class="comment-form-comment"><label for="test">' . _x( 'Comment', 'noun' ) . '</label> <textarea id="comment" name="test" cols="45" rows="8" aria-required="true"></textarea></p>',
    		'must_log_in'          => '<p class="must-log-in">' . sprintf( __( 'You must be <a href="%s">logged in</a> to post a comment.' ), wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>',
    		'logged_in_as'         => '<p class="logged-in-as">' . sprintf( __( 'Logged in as <a href="%1$s">%2$s</a>. <a href="%3$s" title="Log out of this account">Log out?</a>' ), get_edit_user_link(), $user_identity, wp_logout_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>',
    		'comment_notes_before' => '<p class="comment-notes">' . __( 'Your email address will not be published.' ) . ( $req ? $required_text : '' ) . '</p>',
    		'comment_notes_after'  => '<p class="form-allowed-tags">' . sprintf( __( 'You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: %s' ), ' <code>' . allowed_tags() . '</code>' ) . '</p>',
    		'id_form'              => 'commentform',
    		'id_submit'            => 'submit',
    		'title_reply'          => __( 'Leave a Reply' ),
    		'title_reply_to'       => __( 'Leave a Reply to %s' ),
    		'cancel_reply_link'    => __( 'Cancel reply' ),
    		'label_submit'         => __( 'Post Comment' ),
    		'format'               => 'xhtml',

    And here i edit the ‘test’ in the comments.php from the theme

    <?php $comment_args = array( 'title_reply'=>'Got Something To Say:',
    'fields' => apply_filters( 'comment_form_default_fields', array(
    'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Your Good Name' ) . '</label> ' . ( $req ? '<span>*</span>' : '' ) .
            '<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' /></p>',  
        'email'  => '<p class="comment-form-email">' .
                    '<label for="email">' . __( 'Your Email Please' ) . '</label> ' .
                    ( $req ? '<span>*</span>' : '' ) .
                    '<input id="email" name="email" type="text" value="' . esc_attr(  $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . ' />'.'</p>',
        'url'    => '' ) ),
        'comment_field' => '<p>' .
                    '<label for="comment">' . __( 'Let us know what you have to say:' ) . '</label>' .
                    '<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea>' .
        'comment_notes_after' => '',
            'test' => '<p>' .
                    '<label for="test">' . __( 'Hoe maak je kaas?:' ) . '</label>' .
                    '<textarea id="test" name="test" cols="45" rows="8" aria-required="true"></textarea>' .
        'comment_notes_after' => '',
    comment_form($comment_args); ?>

Viewing 15 replies - 31 through 45 (of 80 total)
  • Moderator bcworkz


    What I’m trying to determine is who is seeing the input values. You have 6 different forms, which one is used is determined by some criteria. For example: User A has a certain attribute such that he is served form 1. User B has a different attribute so is served form 2. They each fill out the form and submit at approximately the same time. User B’s page reloads, showing previously submitted comments. User B sees his just submitted comment. Will user B ever see what user A submitted?

    If no, we’re good, if yes, the twentyten_comments() will get rather involved and need to work for all 6 conditions.

    No. User A can not see the comments from user B. And B can not see A.

    But both have the same 6 forms. With the same information.

    i tryed the code that you posted and changed the following test to bcw_test <input type=”text” name=”bcw_test” id=”bcw_test” size=”22″ />

    And i dont see the following in the template folder: wp-comments-post.php
    As you placed it here: <form action=”<?php echo site_url( ‘/wp-comments-post.php’ ); ?>”…..

    Im getting the following error when i press on the submit button:
    FAILED: you have no written response.

    I placed the following code in the comments.php for the output to be shown:

    <ol class="commentlist">
    					/* Loop through and list the comments. Tell wp_list_comments()
    					 * to use twentyten_comment() to format the comments.
    					 * If you want to overload this in a child theme then you can
    					 * define twentyten_comment() and that will be used instead.
    					 * See twentyten_comment() in twentyten/functions.php for more.
    					wp_list_comments( array( 'callback' => 'twentyten_comment' ) );
    					if( current_user_can('like_cheese')) echo 'Favorite cheese? <input type="text" name="bcw_test" id="bcw_test" size="22" />';
    else if( current_user_can('like_flowers')) echo 'Favorite flower? <input type="text" name="bcw_test" id="bcw_test" size="22" />';
    else echo 'What do you like? <input type="text" name="bcw_test" id="bcw_test" size="22" />';
    				<?php echo get_comment_meta( $comment->comment_ID, 'bcw_test', true ); ?>

    Moderator bcworkz


    The added code in your last snippet is in the wrong place, it will not do what it is supposed to do there, as it is outside the <form> tags, so the entered value is not included in the POST data sent with the submit button. It is also outside the comments loop so the values for each comment will not display.

    I see my previous instructions were somewhat flawed, let’s try again 🙁 Move this current file you’re working on somewhere safe for reference and make a fresh copy of your twentyten theme’s comments.php. Be sure your child theme’s functions.php page still has the bcw_handle_comment($id) save values function. Don’t change anything else just yet except as instructed here. Do not change the input field name from “test”, it must be coordinated with the save values function which uses only “test”. Do not use any of the if( current_user_can('like_cheese')) code. It has no use in this scheme. Let’s get just the basic test field working all the way around. You can add real fields after that.

    Copy the twentyten_comments() function definition to your copy of comments.php, assigning a new function name. Also use this new name in the line wp_list_comments( array( 'callback' => 'twentyten_comment' ) );

    Inside the renamed twentyten_comments() function definition, place this Test: <?php echo get_comment_meta( $comment->comment_ID, 'bcw_test', true ); ?> line above the existing <div class="reply"> line. I added the “Test: ” text so you can see where the field is placed on the actual page even if there is no data to display. The ‘bcw_test’ label is correct here despite ‘test’ being used elsewhere. It too is coordinated in the save values function.

    Finally, replace the <?php comment_form(); ?> line with this revised version:

    <?php $post_id = get_the_ID();
    	if ( comments_open( $post_id ) ) : ?>
    	<div id="respond" class="comment-respond">
    		<h3 id="reply-title" class="comment-reply-title"><?php comment_form_title(__( 'Leave a Reply' ),__( 'Leave a Reply to %s' )); ?> <small><?php cancel_comment_reply_link(__( 'Cancel reply' )); ?></small></h3>
    		<?php if ( get_option( 'comment_registration' ) && !is_user_logged_in() ) : ?>
    			<?php echo '<p class="must-log-in">' . sprintf( __( 'You must be <a href="%s">logged in</a> to post a comment.' ), wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>'; ?>
    		<?php else : ?>
    			<form action="<?php echo site_url( '/wp-comments-post.php' ); ?>" method="post" id="<?php echo 'commentform'; ?>" class="comment-form">
    				<?php $args = '<p class="logged-in-as">' . sprintf( __( 'Logged in as <a href="%1$s">%2$s</a>. <a href="%3$s" title="Log out of this account">Log out?</a>' ), get_edit_user_link(), $user_identity, wp_logout_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>';
    				echo apply_filters( 'comment_form_logged_in', $args, $commenter, $user_identity ); ?>
    				<?php $args = '<p class="comment-form-comment"><label for="comment">' . _x( 'Comment', 'noun' ) . '</label> <textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea></p>';
    				echo apply_filters( 'comment_form_field_comment', $args ); ?>
    				Test <input type="text" name="test" id="test" size="22" /><br style="clear: both;"><br>
    				<p class="form-submit">
    					<input name="submit" type="submit" id="<?php echo esc_attr( $args['id_submit'] ); ?>" value="<?php echo __( 'Post Comment' ); ?>" />
    					<?php comment_id_fields( $post_id ); ?>
    		<?php endif; ?>
    	</div><!-- #respond -->
    <?php else :
    	do_action( 'comment_form_comments_closed' );
    endif; ?>

    In my earlier haste, I overlooked some little tricks used in the original code which threw some errors. All tested and working now. This all should yield a functioning test field in the comments.

    FYI, there should not be a wp-comments-post.php template. This file resides in the root WP folder and contains core comment code, it is not a template. It is the code that handles the the comment form data after the submit button is clicked.

    Fingers crossed…

    Thats what i have now in the comment.php but when i press on submit it only loads and puts the following at the domain name: test3/#ajaxed-comments

    Fucntion.php i left like this:

    Moderator bcworkz


    On comments.php:
    1. Replace this:
    <?php echo get_comment_meta( $comment->comment_ID, 'bcw_test', true ); ?>

    with this:
    <?php wp_list_comments( array( 'callback' => 'twentyten_comment1' ) ); ?>

    Note that ‘twentyten_comment’ has a ‘1’ added to the name.

    2. At the very bottom of comments.php type “<?php” (without the quotes)

    Copy the entire function definition for twentyten_comment() from functions.php and place it at the very bottom of comments.php after the “<?php“.

    Rename the function ‘twentyten_comment’ to ‘twentyten_comment1’

    Erase the endif; at the very bottom of the copied function definition.

    On functions.php:
    3. The only thing on this page should be:

    //Save the extra comment field value
    <?php function bcw_handle_comment($id) {
       if (array_key_exists('test', $_POST))
          update_comment_meta( $id, 'bcw_test', $_POST['test']);
    add_action('wp_insert_comment', 'bcw_handle_comment');

    Dangerously close to getting this working.

    it gives me this error: Parse error: syntax error, unexpected $end in

    when i add the following code to function.php it will not give me this error but it doesn’t work…

    //Save the extra comment field value
    function bcw_handle_comment($id) {
       if (array_key_exists('test', $_POST))
          update_comment_meta( $id, 'bcw_test', $_POST['test']);
    add_action('wp_insert_comment', 'bcw_handle_comment');
    //Override default theme function to display a comment

    I did add: endif; but than i get this at the adress again: (#ajaxed-comments)

    Moderator bcworkz


    You do not want the endif; there. It was the companion to if ( !function_exists('twentyten_comments') ) :. You should not have either line anymore on either page.

    That error usually means there is an imbalance with parenthesis or brackets, there is no such error in the posted snippet. It loads fine when pasted into my functions.php. Where did the error message report the error to be? functions.php or comments.php? What code corresponds to the line number? Note the actual error is sometimes above the quoted line. The quoted line is where the parser figured out there is a problem.

    Imbalanced parenthesis can be hard to find. A programmers editor that highlights parenthesis pairs helps immensely. You still need to move the cursor to each parenthesis in turn and locate it’s companion and decide if the indicated pair is appropriate or not. Which means you need some understanding of what the code is supposed to do.

    Parse error: syntax error, unexpected $end in /nfs/home/deb11111/domains/ on line 600

    I can see that you tested it with a clean copy of the twentyten?

    If this is true then please paste your comment.php and function.php so i can see what i’m doing wrong. I know your learning me but my deadline is almost over. I just need this fields to work. If i can add fields to mutiple comment.php(and it works) than im saved. After that i can test and learn more 🙂

    Moderator bcworkz


    I don’t know what’s going on with this error. Your version of functions.php works perfectly on my installation. Do you have a clean copy of this file from before we started all of this? This is the only code that should be added to functions.php:

    //Save the extra comment field value
    function bcw_handle_comment($id) {
       if (array_key_exists('test', $_POST))
          update_comment_meta( $id, 'bcw_test', $_POST['test']);
    add_action('wp_insert_comment', 'bcw_handle_comment');

    Nothing else, not even the added code in twentyten_comment().

    All other modifications are on comments.php. The version that’s tested and fully functional is in pastebin: comments.php

    I’ve added notes to make it easy for you to know where to edit in your actual fields. There’s two spots on this file, and the field names need to be coordinated with saving the values in bcw_handle_comment().

    Though I used twentyten as a base for the replacement comment form, it was actually tested in my custom child theme based on twentyeleven. To ensure there is no more confusion or errors, the copy in paste bin is a freshly coded version based on twentyten v1.6. I even switched my installation to twentyten theme to fully test. Everything worked flawlessly!

    To summarize, you only need to do two things to get a functional test field. Add the bcw_handle_comment() code to a clean error free copy of functions.php. And replace comments.php with the pastebin version.

    Good luck!

    I did all you named above. I also installed a clean version(1.6) of the theme.

    Fatal error: Cannot redeclare twentyten_comment1() (previously declared in /nfs/home/deb11111/domains/ in /nfs/home/deb11111/domains/ on line 200

    Ow i copyed some more info.. pastebin is not giving the error above anymore but will not make my output on the page : #ajaxed-comments

    testing some more

    weird think is that i get the new test field but also the original responds field.

    This is the code for the new “clean” function.php:

    Moderator bcworkz


    I confirmed your latest functions.php works fine with my pastebin comments.php in the twentyten theme on my installation. Even though it sounds like there’s other problems, are you at least seeing the Test: input field and you are able to enter a value and that value is saved and displayed with each related comment?

    If that is the case we’ve accomplished the main functionality. I don’t understand when you say “will not make my output on the page : #ajaxed-comments”. What output are you expecting? What is the #ajax-comments page?

    And about “the original responds field”? Is this the large text box where one normally enters comment text? You do not want this? To get rid of it delete line 139 of my pastebin version of comments.php that reads: <div class="comment-body"><?php comment_text(); ?></div>

    You actually can’t easily get rid of this because doing so throws errors. What you can do is hide it with CSS entered on styles.css:

    .comment-form-comment {
    	display: none;

    The other problem is if no comment is entered an error is thrown. You can get around this by putting default text in the textarea. Add some text in front of </textarea> near the end of line 87.

    Even with this, any given user can only enter a single comment, after which the comment will be flagged as a duplicate. There’s a hook we can use to suppress this, but I’m not sure where it is right now. If this is indeed what you want to do I will take the time to identify the hooks needed to make hiding the textarea work well. Let me know if this is what you want to do.

Viewing 15 replies - 31 through 45 (of 80 total)
  • The topic ‘Add a comment field’ is closed to new replies.