Support » Plugins » Hacks » Add a comment field

  • Resolved Taro

    (@sicktb)


    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

    add_filter('comment_form_default_fields','add_comment_fields');
    
    function comment_form( $args = array(), $post_id = null ) {
    	if ( null === $post_id )
    		$post_id = get_the_ID();
    	else
    		$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>' .
    
                    '</p>',
    
        '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>' .
    
                    '</p>',
    
        'comment_notes_after' => '',
    
    );
    
    comment_form($comment_args); ?>

Viewing 15 replies - 1 through 15 (of 80 total)
  • Taro

    (@sicktb)

    Some more information.

    I replaced the code
    <?php comment_form(); ?>

    With the code:

    <?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>' .
    
                    '</p>',
    
        '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>' .
    
                    '</p>',
    
        'comment_notes_after' => '',
    
    );
    
    comment_form($comment_args); ?>

    Why? I need to make different comments-forms on all pages.

    With kind regards,
    Taro

    Taro

    (@sicktb)

    http://blog.ideashower.com/post/15147134893/wordpress-plugin-extra-comment-fields

    This maybe helps me but i think its not up to date…

    [Moderator Note: Please ensure that you are embedding links correctly in your posts.]

    Moderator bcworkz

    (@bcworkz)

    Please do not alter your core installation files, you will sooner or later regret this choice. In this case it is not required, there are clean ways to alter the comment form.

    You can alter your theme files if you like, but if it is a maintained theme with updates, you should create a child theme to protect your changes.

    To alter the comment form (or hack WP in general), you hook into a filter or action to alter how things work.

    To alter the default form, hook the ‘comment_form_defaults’ filter and alter the definition array passed to your callback. There are also filters for each individual default field if that works better for you.

    To add additional fields, you could add them to the defaults as mentioned above, or hook the ‘comment_form’ action and echo out whatever HTML you want to appear at the bottom of the form. This will appear after the submit button but still inside the form.

    The code for this can be added to your child theme functions.php, or you could create a simple custom plugin to contain the code.

    Taro

    (@sicktb)

    Ok so i should not edit the comment-template.php

    Meaning i can only edit the comments.php and function.php

    <?php comment_form(); ?> <- this code should be removed and replaced by the code i pased. Above in my 2nd post. But as you told me bcworkz. I can add additional fields useing the defaults. But what if i need to ad like 10 more fields? I need to add more array’s somehow with out addign the core files.

    Is this done in the function.php? And if so.. how? 😉

    Taro

    (@sicktb)

    I think i found it with the following plugin: http://blog.ideashower.com/post/15147134893/wordpress-plugin-extra-comment-fields

    But when i get to the part to show the result from the command im a bit lost…The code below is from mij comment.php i did ad the code:
    test?: <?php print $comment->extra_test; ?>

    <?php
    /**
     * The template for displaying Comments.
     *
     * The area of the page that contains both current comments
     * and the comment form. The actual display of comments is
     * handled by a callback to twentyten_comment which is
     * located in the functions.php file.
     *
     * @package WordPress
     * @subpackage Twenty_Ten
     * @since Twenty Ten 1.0
     */
    ?>
    
    			<div id="comments">
    <?php if ( post_password_required() ) : ?>
    				<p class="nopassword"><?php _e( 'This post is password protected. Enter the password to view any comments.', 'twentyten' ); ?></p>
    			</div><!-- #comments -->
    <?php
    		/* Stop the rest of comments.php from being processed,
    		 * but don't kill the script entirely -- we still have
    		 * to fully load the template.
    		 */
    		return;
    	endif;
    ?>
    
    <?php
    	// You can start editing here -- including this comment!
    ?>
    
    <?php if ( have_comments() ) : ?>
    			<h3 id="comments-title"><?php
    			printf( _n( 'One Response to %2$s', '%1$s Responses to %2$s', get_comments_number(), 'twentyten' ),
    			number_format_i18n( get_comments_number() ), '<em>' . get_the_title() . '</em>' );
    			?></h3>
    
    <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // Are there comments to navigate through? ?>
    			<div class="navigation">
    				<div class="nav-previous"><?php previous_comments_link( __( '<span class="meta-nav">←</span> Older Comments', 'twentyten' ) ); ?></div>
    				<div class="nav-next"><?php next_comments_link( __( 'Newer Comments <span class="meta-nav">→</span>', 'twentyten' ) ); ?></div>
    			</div> <!-- .navigation -->
    <?php endif; // check for comment navigation ?>
    
    			<ol class="commentlist">
    				<?php
    					/* 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' ) );
    				?>
    
    			test?: <?php print $comment->extra_test; ?>
    
    <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // Are there comments to navigate through? ?>
    			<div class="navigation">
    				<div class="nav-previous"><?php previous_comments_link( __( '<span class="meta-nav">←</span> Older Comments', 'twentyten' ) ); ?></div>
    				<div class="nav-next"><?php next_comments_link( __( 'Newer Comments <span class="meta-nav">→</span>', 'twentyten' ) ); ?></div>
    			</div><!-- .navigation -->
    <?php endif; // check for comment navigation ?>
    
    	<?php
    	/* If there are no comments and comments are closed, let's leave a little note, shall we?
    	 * But we only want the note on posts and pages that had comments in the first place.
    	 */
    	if ( ! comments_open() && get_comments_number() ) : ?>
    		<p class="nocomments"><?php _e( 'Comments are closed.' , 'twentyten' ); ?></p>
    	<?php endif;  ?>
    
    <?php endif; // end have_comments() ?>
    
    <?php comment_form(); ?>
    <p><input type="text" name="test" id="test" size="22" />
    <label for="url"><small>test</small></label></p>
    
    </div><!-- #comments --></blockquote>
    </a>

    [Moderator Note: Please post code or markup between backticks or use the code button. Or better still – use a pastebin. Your posted code may now have been permanently damaged by the forum’s parser.]

    Taro

    (@sicktb)

    I think i found it with the following plugin: http://blog.ideashower.com/post/15147134893/wordpress-plugin-extra-comment-fields

    But when i get to the part to show the result from the command im a bit lost…The code below is from mij comment.php i did ad the code:
    test?: <?php print $comment->extra_test; ?>

    <?php
    /**
     * The template for displaying Comments.
     *
     * The area of the page that contains both current comments
     * and the comment form. The actual display of comments is
     * handled by a callback to twentyten_comment which is
     * located in the functions.php file.
     *
     * @package WordPress
     * @subpackage Twenty_Ten
     * @since Twenty Ten 1.0
     */
    ?>
    
    			<div id="comments">
    <?php if ( post_password_required() ) : ?>
    				<p class="nopassword"><?php _e( 'This post is password protected. Enter the password to view any comments.', 'twentyten' ); ?></p>
    			</div><!-- #comments -->
    <?php
    		/* Stop the rest of comments.php from being processed,
    		 * but don't kill the script entirely -- we still have
    		 * to fully load the template.
    		 */
    		return;
    	endif;
    ?>
    
    <?php
    	// You can start editing here -- including this comment!
    ?>
    
    <?php if ( have_comments() ) : ?>
    			<h3 id="comments-title"><?php
    			printf( _n( 'One Response to %2$s', '%1$s Responses to %2$s', get_comments_number(), 'twentyten' ),
    			number_format_i18n( get_comments_number() ), '<em>' . get_the_title() . '</em>' );
    			?></h3>
    
    <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // Are there comments to navigate through? ?>
    			<div class="navigation">
    				<div class="nav-previous"><?php previous_comments_link( __( '<span class="meta-nav">&larr;</span> Older Comments', 'twentyten' ) ); ?></div>
    				<div class="nav-next"><?php next_comments_link( __( 'Newer Comments <span class="meta-nav">&rarr;</span>', 'twentyten' ) ); ?></div>
    			</div> <!-- .navigation -->
    <?php endif; // check for comment navigation ?>
    
    			<ol class="commentlist">
    				<?php
    					/* 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' ) );
    				?>
    
    			test?: <?php print $comment->extra_test; ?>
    
    			</ol>
    
    <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // Are there comments to navigate through? ?>
    			<div class="navigation">
    				<div class="nav-previous"><?php previous_comments_link( __( '<span class="meta-nav">&larr;</span> Older Comments', 'twentyten' ) ); ?></div>
    				<div class="nav-next"><?php next_comments_link( __( 'Newer Comments <span class="meta-nav">&rarr;</span>', 'twentyten' ) ); ?></div>
    			</div><!-- .navigation -->
    <?php endif; // check for comment navigation ?>
    
    	<?php
    	/* If there are no comments and comments are closed, let's leave a little note, shall we?
    	 * But we only want the note on posts and pages that had comments in the first place.
    	 */
    	if ( ! comments_open() && get_comments_number() ) : ?>
    		<p class="nocomments"><?php _e( 'Comments are closed.' , 'twentyten' ); ?></p>
    	<?php endif;  ?>
    
    <?php endif; // end have_comments() ?>
    
    <?php comment_form(); ?>
    <p><input type="text" name="test" id="test" size="22" />
    <label for="url"><small>test</small></label></p>
    
    </div><!-- #comments -->

    Moderator bcworkz

    (@bcworkz)

    That plugin has not been maintained in quite sometime, it appears the standard way of adding fields may have changed since then. Following the instructions, the added field values will never be sent to the server since the fields are outside of the <form> tags. The main thing this plugin did was to simplify the saving and retrieving extra field values. If you can figure out how to add fields, you can figure out this part too.

    So we are back to your own custom code. It can indeed reside in your theme’s functions.php file. You can add as many fields as you like to the default definition array. Add another key/value pair for each field. Code to add one field looks like this:

    function add_bcw_fields($fields){
    	$fields['test'] = '<input type="text" name="test" id="test" size="22" />';
    	return $fields;
    }
    add_filter( 'comment_form_default_fields', 'add_bcw_fields' );

    Once you’ve added your fields, you need to put the submitted data somewhere. A good hook to use is ‘pre_comment_on_post’. You get the data from $_POST just as you would for any other form. You can put the data anywhere that makes sense, commentmeta is typically used.

    Once the data is saved, you might want to display this data along with the comments. For this you alter the theme’s comment walker function, or override it in your child theme by redefining it. The name of the walker function is typically passed to the wp_list_comments() call on comments.php as the ‘callback’ argument and the walker function itself is usually defined on the functions.php file, though this can vary by theme.

    To output the stored data, grab the data from where ever you stored it and sprintf() it where appropriate in the HTML stream output by the walker function.

    Taro

    (@sicktb)

    Dear bcworkz,

    Your gonna make me happy! Im almoost there i think…

    This is what i have in my function.php.
    I placed the following codes in 2 places in the function.php to test. But this isnt working:

    <?php print $comment->test; ?>

    function add_bcw_fields($fields){
    	$fields['test'] = '<input type="text" name="test" id="test" size="22" />';
    	return $fields;
    }
    add_filter( 'comment_form_default_fields', 'add_bcw_fields' );
    
    function twentyten_comment( $comment, $args, $depth ) {
    	$GLOBALS['comment'] = $comment;
    	switch ( $comment->comment_type ) :
    		case '' :
    	?>
    	<li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
    		<div id="comment-<?php comment_ID(); ?>"><?php echo $comment->test; ?>
    
    			<div class="comment-author vcard">
    				<?php echo get_avatar( $comment, 40 ); ?>
    				<?php printf( __( '%s <span class="says">says:</span>', 'twentyten' ), sprintf( '<cite class="fn">%s</cite>', get_comment_author_link() ) ); ?>
    			</div><!-- .comment-author .vcard -->
    			<?php if ( $comment->comment_approved == '0' ) : ?>
    				<em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'twentyten' ); ?></em>
    				<br />
    			<?php endif; ?>
    
    			<div class="comment-meta commentmetadata"><a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>">
    				<?php
    					/* translators: 1: date, 2: time */
    					printf( __( '%1$s at %2$s', 'twentyten' ), get_comment_date(),  get_comment_time() ); ?></a><?php edit_comment_link( __( '(Edit)', 'twentyten' ), ' ' );
    				?>
    			</div><!-- .comment-meta .commentmetadata -->
    
    			<div class="comment-body"><?php comment_text(); ?><?php print $comment->test; ?></div>
    
    			<div class="reply">
    				<?php /* <?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?> */ ?>
    			</div><!-- .reply -->
    		</div><!-- #comment-##  -->
    
    	<?php
    			break;
    		case 'pingback'  :
    		case 'trackback' :
    	?>
    	<li class="post pingback">
    		<p><?php _e( 'Pingback:', 'twentyten' ); ?> <?php comment_author_link(); ?><?php edit_comment_link( __( '(Edit)', 'twentyten' ), ' ' ); ?></p>
    	<?php
    			break;
    	endswitch;
    }
    endif;
    Moderator bcworkz

    (@bcworkz)

    Yes, you are getting closer. But you missed a crucial point. The comment system does not automatically process added fields for you, you must handle them yourself. An honest oversight, sometimes such things are handled for you, such as with the Settings API.

    Thus you cannot expect your added fields to be part of $comment. A $comment->test value does not exist. In fact, as it stands, the value you placed in the test field was never saved. It’s your responsibility to do so.

    My suggestion on how to save the field data in my previous post was not the best advice, though it would have worked. On further consideration a better hook is the ‘wp_insert_comment’ action. This way the data is only inserted if the comment checks out and is actually inserted. Save the data with something like this:

    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');

    Finally, to display this data in the comment list, insert the following in the twentyten_comment() function where ever it makes sense:
    <?php echo get_comment_meta( $comment->comment_ID, 'bcw_test', true ); ?>

    Not to make more work for you, but you will see this added field is not visible at all in the backend, much less editable. As it stands, the only way to view the field is to look at the comments page, and to edit by using phpMyAdmin. It is possible to add extra columns to the comments table, though a bit tricky. Though I haven’t done so, you can also add a metabox to the edit-comment screen that allows admin editing of the field. If and when you are ready to pursue such enhancements, I’m willing to try and help as needed.

    Taro

    (@sicktb)

    Though I haven’t done so, you can also add a metabox to the edit-comment screen that allows admin editing of the field.

    This would make it all easyer. But my main point now is to get it to work that the customer(client) can see what he/she posted. As a admin i just need to remove the comment when needed.

    Do i still need this in the comment.php?

    <?php comment_form(); ?>
    
    <p><input type="text" name="bcw_test" id="bcw_test" size="22" />
    <label for="url"><small>test</small></label></p>
    
    </div><!-- #comments -->

    Total function.php code now: This will not give me a new comment fiel to type. I can only see the comment field that i placed in the comment.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');
    
    function twentyten_comment( $comment, $args, $depth ) {
    	$GLOBALS['comment'] = $comment;
    	switch ( $comment->comment_type ) :
    		case '' :
    	?>
    	<li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
    		<div id="comment-<?php comment_ID(); ?>">
    
    			<div class="comment-author vcard">
    				<?php echo get_avatar( $comment, 40 ); ?>
    				<?php printf( __( '%s <span class="says">says:</span>', 'twentyten' ), sprintf( '<cite class="fn">%s</cite>', get_comment_author_link() ) ); ?>
    			</div><!-- .comment-author .vcard -->
    			<?php if ( $comment->comment_approved == '0' ) : ?>
    				<em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'twentyten' ); ?></em>
    				<br />
    			<?php endif; ?>
    
    			<div class="comment-meta commentmetadata"><a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>">
    				<?php
    					/* translators: 1: date, 2: time */
    					printf( __( '%1$s at %2$s', 'twentyten' ), get_comment_date(), get_comment_time() ); ?></a><?php edit_comment_link( __( '(Edit)', 'twentyten' ), ' ' );
    				?>
    			</div><!-- .comment-meta .commentmetadata -->
    
    			<div class="comment-body"><?php comment_text(); ?></div>
                <?php echo get_comment_meta( $comment->comment_ID, 'bcw_test', true ); ?>
    
    			<div class="reply">
    				<?php /* <?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?> */ ?>
    			</div><!-- .reply -->
    		</div><!-- #comment-##  -->
    
    	<?php
    			break;
    		case 'pingback'  :
    		case 'trackback' :
    	?>
    	<li class="post pingback">
    		<p><?php _e( 'Pingback:', 'twentyten' ); ?> <?php comment_author_link(); ?><?php edit_comment_link( __( '(Edit)', 'twentyten' ), ' ' ); ?></p>
    	<?php
    			break;
    	endswitch;
    }
    endif;
    
    /**
     * Register widgetized areas, including two sidebars and four widget-ready columns in the footer.
     *
     * To override twentyten_widgets_init() in a child theme, remove the action hook and add your own
     * function tied to the init hook.
     *
     * @since Twenty Ten 1.0
     * @uses register_sidebar
     */
    function twentyten_widgets_init() {
    	// Area 1, located at the top of the sidebar.
    	register_sidebar( array(
    		'name' => __( 'Primary Widget Area', 'twentyten' ),
    		'id' => 'primary-widget-area',
    		'description' => __( 'Add widgets here to appear in your sidebar.', 'twentyten' ),
    		'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
    		'after_widget' => '</li>',
    		'before_title' => '<h3 class="widget-title">',
    		'after_title' => '</h3>',
    	) );
    
    	// Area 2, located below the Primary Widget Area in the sidebar. Empty by default.
    	register_sidebar( array(
    		'name' => __( 'Secondary Widget Area', 'twentyten' ),
    		'id' => 'secondary-widget-area',
    		'description' => __( 'An optional secondary widget area, displays below the primary widget area in your sidebar.', 'twentyten' ),
    		'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
    		'after_widget' => '</li>',
    		'before_title' => '<h3 class="widget-title">',
    		'after_title' => '</h3>',
    	) );
    
    	// Area 3, located in the footer. Empty by default.
    	register_sidebar( array(
    		'name' => __( 'First Footer Widget Area', 'twentyten' ),
    		'id' => 'first-footer-widget-area',
    		'description' => __( 'An optional widget area for your site footer.', 'twentyten' ),
    		'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
    		'after_widget' => '</li>',
    		'before_title' => '<h3 class="widget-title">',
    		'after_title' => '</h3>',
    	) );
    
    	// Area 4, located in the footer. Empty by default.
    	register_sidebar( array(
    		'name' => __( 'Second Footer Widget Area', 'twentyten' ),
    		'id' => 'second-footer-widget-area',
    		'description' => __( 'An optional widget area for your site footer.', 'twentyten' ),
    		'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
    		'after_widget' => '</li>',
    		'before_title' => '<h3 class="widget-title">',
    		'after_title' => '</h3>',
    	) );
    
    	// Area 5, located in the footer. Empty by default.
    	register_sidebar( array(
    		'name' => __( 'Third Footer Widget Area', 'twentyten' ),
    		'id' => 'third-footer-widget-area',
    		'description' => __( 'An optional widget area for your site footer.', 'twentyten' ),
    		'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
    		'after_widget' => '</li>',
    		'before_title' => '<h3 class="widget-title">',
    		'after_title' => '</h3>',
    	) );
    
    	// Area 6, located in the footer. Empty by default.
    	register_sidebar( array(
    		'name' => __( 'Fourth Footer Widget Area', 'twentyten' ),
    		'id' => 'fourth-footer-widget-area',
    		'description' => __( 'An optional widget area for your site footer.', 'twentyten' ),
    		'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
    		'after_widget' => '</li>',
    		'before_title' => '<h3 class="widget-title">',
    		'after_title' => '</h3>',
    	) );
    }
    /** Register sidebars by running twentyten_widgets_init() on the widgets_init hook. */
    add_action( 'widgets_init', 'twentyten_widgets_init' );
    
    /**
     * Removes the default styles that are packaged with the Recent Comments widget.
     *
     * To override this in a child theme, remove the filter and optionally add your own
     * function tied to the widgets_init action hook.
     *
     * This function uses a filter (show_recent_comments_widget_style) new in WordPress 3.1
     * to remove the default style. Using Twenty Ten 1.2 in WordPress 3.0 will show the styles,
     * but they won't have any effect on the widget in default Twenty Ten styling.
     *
     * @since Twenty Ten 1.0
     */
    function twentyten_remove_recent_comments_style() {
    	add_filter( 'show_recent_comments_widget_style', '__return_false' );
    }
    add_action( 'widgets_init', 'twentyten_remove_recent_comments_style' );
    
    if ( ! function_exists( 'twentyten_posted_on' ) ) :
    /**
     * Prints HTML with meta information for the current post-date/time and author.
     *
     * @since Twenty Ten 1.0
     */
    function twentyten_posted_on() {
    	printf( __( '<span class="%1$s">Posted on</span> %2$s <span class="meta-sep">by</span> %3$s', 'twentyten' ),
    		'meta-prep meta-prep-author',
    		sprintf( '<a href="%1$s" title="%2$s" rel="bookmark"><span class="entry-date">%3$s</span></a>',
    			get_permalink(),
    			esc_attr( get_the_time() ),
    			get_the_date()
    		),
    		sprintf( '<span class="author vcard"><a class="url fn n" href="%1$s" title="%2$s">%3$s</a></span>',
    			get_author_posts_url( get_the_author_meta( 'ID' ) ),
    			esc_attr( sprintf( __( 'View all posts by %s', 'twentyten' ), get_the_author() ) ),
    			get_the_author()
    		)
    	);
    }
    endif;
    
    if ( ! function_exists( 'twentyten_posted_in' ) ) :
    /**
     * Prints HTML with meta information for the current post (category, tags and permalink).
     *
     * @since Twenty Ten 1.0
     */
    function twentyten_posted_in() {
    	// Retrieves tag list of current post, separated by commas.
    	$tag_list = get_the_tag_list( '', ', ' );
    	if ( $tag_list ) {
    		$posted_in = __( 'This entry was posted in %1$s and tagged %2$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'twentyten' );
    	} elseif ( is_object_in_taxonomy( get_post_type(), 'category' ) ) {
    		$posted_in = __( 'This entry was posted in %1$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'twentyten' );
    	} else {
    		$posted_in = __( 'Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'twentyten' );
    	}
    	// Prints the string, replacing the placeholders.
    	printf(
    		$posted_in,
    		get_the_category_list( ', ' ),
    		$tag_list,
    		get_permalink(),
    		the_title_attribute( 'echo=0' )
    	);
    }
    endif;

    Moderator bcworkz

    (@bcworkz)

    I was pointing out the possibilities for full functionality, it’s up to you to decide if it’s worth doing or not. Either way, we need to get basic functionality before attacking any non-essential features 🙂

    Yes, remove the added field code on comment.php. Though you can see the field, it is outside the <form> tags so any input is never sent to the server when the form is submitted.

    Your latest version of the code is missing the add_bcw_fields() code. This is the code that displays the field in the form. (At some point you will want to add labels and other bits to the input field so it fits seamlessly in your form) You need both this and the bcw_handle_comment() code that saves the value to the DB.

    BTW, next time you need to post a big block of code, please use pastebin.com and just provide a link here. Posting large blocks of code (more than a dozen lines) is frowned upon in these forums. Also, the pastebin display has syntax highlighting, making reading many lines of code much easier. For small code snippets though, having the code inline with commentary is less disruptive to read IMO.

    Taro

    (@sicktb)

    Im not sure how to add that 2 lines of code and where…Maybe like this below?

    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’);

    //////////

    <div class=”comment-body”><?php comment_text(); ?></div>
    <div class=”comment-body”><?php add_bcw_fields(); ?></div>
    <div class=”comment-body”><?php bcw_handle_comment(); ?></div>
    <?php echo get_comment_meta( $comment->comment_ID, ‘bcw_test’, true ); ?>

    Moderator bcworkz

    (@bcworkz)

    Not exactly. The code goes in your theme’s functions.php. The rest of the code looks like template code. There are 3 parts to the code I’ve presented at different points, let’s not confuse them, they each do something different, and it matters to some extent where each goes.

    1. echo get_comment_meta( $comment->comment_ID, 'bcw_test', true );
    This goes on any comment template file or function (such as twentyten_comment()) where you want the values stored to be displayed. It must be inside a PHP code block delimited by <?php ?>

    2. bcw_handle_comment(); function definition and it’s associated add_action()
    This function stores the entered value in a DB table when a comment is submitted. It can go anywhere on your theme’s functions.php file, provided it is inside a PHP code block delimited by <?php ?> and it is not inserted inside another function or class definition.

    3. add_bcw_fields(); function definition and it’s associated add_action()
    This function defines the form HTML that displays the field in the comment form. It can go anywhere on your theme’s functions.php file, provided it is inside a PHP code block delimited by <?php ?> and it is not inserted inside another function or class definition.

    This means you do not want this code in your last snippet:

    <div class="comment-body"><?php add_bcw_fields(); ?></div>
    <div class="comment-body"><?php bcw_handle_comment(); ?></div>

    These functions do not output anything, there is no point in calling them from a template or comment display function. They only serve to set things up behind the scenes when their related actions fire.

    In summary, based on the functions.php content you posted earlier, just change that so the first part looks like this:

    // Add extra field to comment form
    function add_bcw_fields($fields){
       $fields['test'] = '<input type="text" name="test" id="test" size="22" />';
       return $fields;
    }
    add_filter( 'comment_form_default_fields', 'add_bcw_fields' );
    //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
    function twentyten_comment( $comment, $args, $depth ) {
       // Code continues...

    You are possibly thinking now “What’s with all the explanations? Just show me how to get this thing working!” I’m hoping you can begin to understand what each bit of code does and how it fits into the overall comment process, which in turn partly determines where each code goes and where it doesn’t.

    The functions called when an action fires can go almost anywhere because their execution only happens when the action actually happens. The code that displays the stored value has to go at a particular spot so the data ends up being displayed in the right place.

    I hope that this finally gets a basic field working so you can start working on some real fields. I hope it all sort of makes sense to you so you can work through the next phase without any perplexing errors. (Errors are inevitable, the difference being if you can resolve them on your own or not). Good luck.

    I think it must be working. But the problem that the field is not showing is because im logged in? The website can only be shown when logged in. So i need to place the correct code… in the correct posistion or edit a line for this field?

    And dont i need to edit this:
    update_comment_meta( $id, ‘bcw_test’, $_POST[‘test’]);
    to:
    update_comment_meta( $id, ‘test’, $_POST[‘test’]);

    http://pastebin.com/embed_js.php?i=LJ7T8gCe

    Moderator bcworkz

    (@bcworkz)

    test vs. bcw_test
    You could store the value under ‘test’ if you like. Just be sure to coordinate with the call to get_comment_meta(), the key used in each must match. I would encourage you to never use plain language words for variable, function, array key and similar PHP names. The risk of name collisions with other plugins increases when this is done. It’s good practice to preface all names with some unique sequence of letters to avoid this.

    I preface all such names in my custom plugin “bcworkz” (it contains many of my WP hacks) with the string ‘bcw_’, the first 3 letters of my plugin name. The snippets I provided came from that plugin. I encourage you to adopt a similar scheme.

    FYI, the input field name does not need to match the metadata key used to store the value, though if it did it might be less confusing. As long as you can keep the different names straight and the code works and the variants are properly coordinated, you can do whatever makes sense to you. I changed my code as little as necessary to illustrate using your test input field instead of my original field, at the same time showing good practice by altering name words used in the DB to avoid name collisions.

    Fields for Logged In Users
    If these fields are only for logged in users, we need to change things up some because the added default fields are never displayed for logged in users. Please replace the current function add_bcw_fields() and the associated add_filter() call with this version:

    // Add extra field to comment form
    function add_bcw_fields(){
       echo '<input type="text" name="test" id="test" size="22" />';
    }
    add_action( 'comment_form_logged_in_after', 'add_bcw_fields' );

    Note that we are now hooking an action instead of a filter, so we echo content instead of returning it. Sorry for any confusion, I simply made a bad assumption about how the fields were to be used.

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