Support » Developing with WordPress » adding and editing non-required field in comments

  • Resolved llizard

    (@llizard)


    In spite of only really knowing enough about php coding to get myself in trouble, I find I cannot stop trying anyway….

    So far, I have managed to introduce an extra field (not required) to my comment form. I have also managed to get the field to appear in the admin area. If the extra field is filled in from the front end, it appears in the editing comment area of admin. However, if the field has not been filled in OR if it is emptied in the editing section of admin, the field remains empty and cannot be edited. (I did try to achieve this using a plugin and ran into exactly the same problem.)

    Staring at various parts of the Codex as well as googling, I am wondering if I need to introduce

    update_post_meta($meta_value); AND/OR update_user_meta( $prev_value )

    For either of these, I am entirely unclear on how to add them to my child theme’s functions file.

    Where have I gone wrong in the following, and/or can someone point to where to find the answer? This is the coding I have put into my child theme’s functions file so far:

        /*...............
        add a field to the comment form
        ...............*/
        function add_comment_fields($newfield) {
            $newfield['webname'] = '<p class="comment-form-author" title="this field is optional"><label for="webname">' . __( 'Website Name' ) . '</label>' .
                '<input id="webname" name="webname" type="text" size="30" /></p>';
            return $newfield;
        }
        add_filter('comment_form_default_fields','add_comment_fields');
    
        // add it to the admin area
        function add_comment_meta_values($comment_id) {
           if ( ( isset( $_POST['webname'] ) ) && ( $_POST['webname'] != '') ) {
                $webname = wp_filter_nohtml_kses($_POST['webname']);
                add_comment_meta($comment_id, 'webname', $webname);
            } 
        }
        add_action ('comment_post', 'add_comment_meta_values', 1);
    
        // attach it to author
        function comment_edit_function( $comment_id )
        {
            if( isset( $_POST['webname'] ) )
              update_comment_meta( $comment_id, 'webname', esc_attr( $_POST['webname'] ) );
        }
        add_filter( 'get_comment_author_link', 'attach_websitename_to_author' );
    
        function attach_websitename_to_author( $author ) {
            $webname = get_comment_meta( get_comment_ID(), 'webname', true );
            if ( $webname )
                $author .= " ($webname)";
            return $author;
        }
    
        // Register meta box on comment edit screen
        function webname_comment_edit_add_meta_box() {
            add_meta_box( 'title', __( 'website name', 'text-domain' ), 'webname_comment_meta_box', 'comment', 'normal', 'high' );
        }
        add_action( 'add_meta_boxes_comment', 'webname_comment_edit_add_meta_box' );
    
        // Callback function for displaying the comment meta box.
        function webname_comment_meta_box( $comment ) {
            $webname = get_comment_meta( $comment->comment_ID, 'webname', true );
            wp_nonce_field( 'webname_comment_fields_update', 'webname_comment_fields_update', false );
            ?>
            <p>
                <label for="webname"><?php _e( 'Website Name', 'text-domain' ); ?></label>
                <input type="text" name="webname" value="<?php echo esc_attr( $webname ); ?>" class="widefat" />
            </p><?php
        }
    
        // Update comment meta data from comment editing screen 
        add_action( 'edit_comment', 'webname_comment_edit_meta_fields' );
        function webname_comment_edit_meta_fields( $comment_id ) {
            if ( ! isset( $_POST['webname_comment_fields_update'] ) || 
                     ! wp_verify_nonce( $_POST['webname_comment_fields_update'], 'webname_comment_fields_update' )
            ) {
                return;
            }
    
          if ( ( isset( $_POST['webname'] ) ) && ( $_POST['webname'] != '' ) ) {
                $webname = wp_filter_nohtml_kses( $_POST['webname'] );
                update_comment_meta( $comment_id, 'webname', $webname );
          } else {
                delete_comment_meta( $comment_id, 'webname');
          }
        }
    
        $webname = get_comment_meta( $comment->comment_ID, 'webname', true );
        echo esc_html( $webname );
    
        /*.......
        for the admin area
         from https://wpengineer.com/2214/adding-input-fields-to-the-comment-form/
         ....*/ 
        function save_comment_meta_data( $comment_id ) {
            add_comment_meta( $comment_id, 'webname', $_POST[ 'webname' ] );
        }
        add_action( 'comment_post', 'save_comment_meta_data' );

    Please note that this is an update on the question I posed in “fixing wordpress” that, on reflection (there have been zero responses), possibly does not belong there.

    Thank you for any help you can offer.

Viewing 10 replies - 16 through 25 (of 25 total)
  • Please excuse me for replying to myself….

    It’s a miracle! I think I got it… in the function, attach_websitename_to_author( $author ), I have to use if( isset( $_POST['webname'] ) ) instead of if ( $webname ). This is so exciting!

    Thank you once again for all your help. It is most appreciated.

    function comment_edit_function( $comment_id )
    {
        if( isset( $_POST['webname'] ) )
          update_comment_meta( $comment_id, 'webname', esc_attr( $_POST['webname'] ) );
    	else 
    	$_POST['webname'] = '&nbsp;';
    }
    
    add_filter( 'get_comment_author_link', 'attach_websitename_to_author' );
    
    function attach_websitename_to_author( $author ) {
        $webname = get_comment_meta( get_comment_ID(), 'webname', true );
    	if( isset( $_POST['webname'] ) )
    //    if ( $webname )
            $author .= " ($webname)";
    	elseif ($_POST['webname'] = '&nbsp;')
    		$author .= " $webname";
    //		$author .= " ";
    		return $author;
     }

    Sigh… I spoke to soon. Back to the drawing board….

    The parentheses are still appearing.

    Moderator bcworkz

    (@bcworkz)

    It’s OK to post updates to you progress. I can tell you’re excited to be making progress and to have some of this coding stuff starting to sink in 🙂

    Remember that comment author link output occurs during a GET request, so there will be nothing in the global $_POST. The author link function is where
    if ( isset( $webname ) && '' != $webname ) {
    comes into play. It was wrong for saving meta, but it’s right in this situation. If that resolves to true, then you append " ($webname)" to $author before returning the link HTML. There is no code for the false or else condition because there is nothing special to do. Of course the function always does return $author; at the end no matter what.

    BTW, when you append data from the DB that will be output, it’s customary to pass the data through an escape function such as esc_html(). This protects your visitors in the off chance your site gets hacked and it inadvertently contains malicious code in the data. $author .= esc_html(" ($webname)");

    re:

    Remember that comment author link output occurs during a GET request, so there will be nothing in the global $_POST.

    I’m guessing that this explains (sort of) why a webname value that is removed in WP_admin, after being entered from outset, remains as '&nbsp;', rather than disappearing.

    Because I have been unable to figure out how to remove the parentheses from those newly empty value fields, I’ve compromised by changing the parentheses to a single tilde: $author .= esc_html(" ~ $webname");. This way, it doesn’t look ridiculous to see “Commenter’sName ~” instead of “Commenter’sName ()”

    I’m completely unclear where to put

    if ($webname = '') || ($webname = ' ') {
      !isset( $webname ) 
    }

    (I don’t even know if !isset is an actual thing….)

    OR

    if ($webname = ' ') {
      $_POST['webname'] = ''; 
    }

    Also, if $webname = '', is it not possible to display the emptiness with emptiness, rather than a tilde (or as before, inside parentheses)?

    I realize that you may well have answered this already; please excuse my obtuseness.
    Babysteps! Babysteps! Thank you again for all your help.

    • This reply was modified 1 month, 1 week ago by llizard.
    Moderator bcworkz

    (@bcworkz)

    Heh, I was trying to get you to work out the final solution to the parentheses quandary by dropping a bunch of hints. One usually learns more that way… or fails. Failure is an option, it’s OK. Second best is stewing on the problem for a while, then peeking at the answers. This ought to do what you want if the no answer state stores an empty string:

    function attach_websitename_to_author( $author ) {
        $webname = get_comment_meta( get_comment_ID(), 'webname', true );
        if ( isset( $webname ) && '' != $webname ) {
            $author .= esc_html(" ($webname)");
        }
        return $author;
     }

    But now it seems your DB has several variants of the no answer state, from no record to empty string, space character, or &nbsp;. Ideally, you ought to update the DB to be consistent. This can be done with phpMyAdmin if you are very careful and first make a backup of the post meta table for safety’s sake, and if there are not too many records to change. Manual editing is relatively safe as long as you stick to only changing the “webname” fields one at a time. It’s possible to change a bunch at one time, but doing so is dangerous unless you are confident with SQL queries.

    If you’d rather not make your DB consistent, we can code for all the possible variants by using the in_array() function, one of my favorites:
    if ( isset( $webname ) && ! in_array( $webname, ['', ' ', '&nbsp;'])) {

    isset() is a legitimate function, but doing !isset( $webname ); on its own doesn’t accomplish anything because the return value is ignored. It’s normally used in conditional statements where the return determines which conditional code to execute. Example:

    if ( isset( $webname )) {
      echo '$webname is set';
    } else {
      echo '$webname is NOT set';
    }

    When we use isset() like this:
    if ( isset( $webname ) && '' != $webname ) {
    it serves to prevent unassigned variable warnings when we do '' != $webname should $webname not be set for any reason.

    Also, if $webname = ”, is it not possible to display the emptiness with emptiness, rather than a tilde (or as before, inside parentheses)?

    You can display whatever you like if it’s coded right 🙂
    Not appending anything to the author link is the same as displaying emptiness, right? That’s what my “answer” code above does. You could add an else condition and append blank spaces, but browsers normally ignore extra spaces, so there’s little point in doing so.

    re:

    Heh, I was trying to get you to work out the final solution to the parentheses quandary by dropping a bunch of hints. One usually learns more that way…

    If it’s any consolation, I did see that the hints were being dropped but I had managed to get myself so mixed up that I failed to get beyond knowing there were arrows pointing to the flashing words “this is a hint”. (I still think I’m getting an inkling about this though…)

    Remarkably, I’m not at all uncomfortable with phpMyAdmin and have managed to remove the extraneous &nbsp; values for $webname. Thank you for spelling out for me which table to save first (I’m a big fan of “save early, save often”) and then remove the offending values.

    I had started to grow attached to the tilde but still decided to returne to the parentheses to go around $webname. When I did that in the functions file, I also removed the extraneous part at the end that was simply a repeat of the add_comment_meta_values($comment_id) function….

    /*.......
     from wpengineer.com/2214/adding-input-fields-to-the-comment-form/
    ....*/ 
    function save_comment_meta_data( $comment_id ) {
        add_comment_meta( $comment_id, 'webname', $_POST[ 'webname' ] );
    }
    add_action( 'comment_post', 'save_comment_meta_data' );

    To test that everything was working, I added a webname value to a comment that didn’t have one. Now I cannot seem to remove it – except via phpMyAdmin. It insists on holding onto the space. (Oh oh….)

    What this means, I’m assuming, is that I have not managed to get the $webname to unset. Am I right that here is my clue for fixing this?

    When we use isset() like this:
    if ( isset( $webname ) && '' != $webname ) {
    it serves to prevent unassigned variable warnings when we do ” != $webname should $webname not be set for any reason.

    Here is the coding I tried, but it does not make it so that the parentheses disappear, nor does it follow the instruction to remove the &nbsp; (because, I guess, the empty value is in the DB???).

    
    function add_comment_meta_values($comment_id) {
       if ( ( isset( $_POST['webname'] ) ) && ( $_POST['webname'] != '') ) {
    	$webname = wp_filter_nohtml_kses($_POST['webname']);
            add_comment_meta($comment_id, 'webname', $webname);
        } 
       if (($_POST[ 'webname' ] = ' ') || ($_POST[ 'webname' ] = '&nbsp;')) {
    	$webname = '';	
       } 
    }
    add_action ('comment_post', 'add_comment_meta_values', 1);

    I was going to try using your array somehow but, well, you know… I’m barely able to tread water to keep breathing as it is.

    • This reply was modified 1 month, 1 week ago by llizard.
    • This reply was modified 1 month, 1 week ago by llizard.
    Moderator bcworkz

    (@bcworkz)

    Since you standardized the DB entries, there’s little reason to use the in_array() right now anyway. Stash it in the back of your mind as a tidy alternative to a series if-x-or-y-or-z-or… statements.

    Getting mixed up with this stuff is par for the course when starting out. When you keep at it it starts to make sense eventually. Needing to make sense of something never really goes away. I still regularly use a special page I built just for testing out code snippets I create to help me understand something. That thing has taught me a lot!

    The parentheses is not managed when data is saved, it’s done upon output. Look at the attach_websitename_to_author() function to manage the appearance of parentheses.

    Your latest “comment_post” callback is not addressing the condition where nothing is submitted or when you try to clear the field. Also, you can strip out extraneous whitespace with the trim() function. This way your code to reduce non-content data to an empty string will be more robust. What if someone entered " &nbsp; "? It’s hard to predict all possible whitespace strings someone might enter, but using clean up functions like trim and kses handles it regardless.

    You have if (($_POST[ 'webname' ] = ' ').... A single = sign in an if conditional is a red flag to me. At times it’s legitimate, but usually it’s a mistake. A single = is an assignment operator. You are assigning the value ' ' to the webname value in $_POST, destroying the originally submitted value. You want to use the double ==, the comparison operator. Nothing is assigned, the two sides are merely compared to see if they have equivalent values.

    Your function logic for saving the webname value should be more like this:

    if ( isset( $_POST['webname'])) {
       $webname = trim( html_entity_decode( wp_filter_nohtml_kses( $_POST[webname])), " \t\n\r\0\x0B\xC2\xA0");
    } else {
       $webname = ''
    }
    add_comment_meta( $comment_id, 'webname', $webname );

    html_entity_decode() converts &nbsp; to the actual non-breaking space character. The " \t\n\r\0\x0B\xC2\xA0" argument for trim() lists all the whitespace characters that should be trimmed from the start or end of strings. \xC2\xA0 is the actual UTF-8 encoding for the non-breaking space character.

    llizard

    (@llizard)

    Thank you again for your reply.

    Getting mixed up with this stuff is par for the course when starting out. When you keep at it it starts to make sense eventually.

    I thought it was making sense, and it’s true that I’m getting glimmerings. But I will have to stare and re-stare at this. I have still failed to be able remove existing &nbsp;‘s except by going into phpMyAdmin.

    But I did manage to get this code to be accepted by noticing that $webname = '' was missing its ending semicolon: $webname = '';

    if ( isset( $_POST['webname'])) {
       $webname = trim( html_entity_decode( wp_filter_nohtml_kses( $_POST[webname])), " \t\n\r\0\x0B\xC2\xA0");
    } else {
       $webname = '';
    }
    add_comment_meta( $comment_id, 'webname', $webname ); 

    So many things to go wrong…. I think I’ll go on a bike ride and maybe, just maybe, it will clear what’s left of my mind, and I’ll suddenly get a breakthrough. 🙂

    • This reply was modified 1 month ago by llizard.
    Moderator bcworkz

    (@bcworkz)

    Argh! Sorry about the missing ;. It’s a frequent recurrence for me, I can’t seem to remember to end statements with it. I’ve a lot of experience in languages that do not use it, but a fair bit with those that do, so I don’t know what my hangup with ; is. Good job sleuthing out the error though. As you discovered, the error messages related to such an error are misleading.

    Good plan to take a break when stuck on something. Sometimes a new thought comes of it, sometimes not, but a break is always good, especially a healthy break like a ride. I took “bike” to mean cycling, but motor biking for pleasure is at least a good mental health exercise.

    I’m unclear what the issue is with &nbsp; still. It shouldn’t be possible to save it with new entries after running data through trim( html_entity_decode()), and I thought they were cleaned out of the existing data.

    llizard

    (@llizard)

    Yes, I did mean a bicycle ride.

    The bike ride was good, but I still don’t understand why &nbsp; is still giving me grief either. I’ll keep picking away at it. I bet it’s something as simple as a misplaced semi-colon! (I know what you mean about how easy it is to miss those. I’ve learned from experience to check for their absence whenever I see an error message saying something like unexpected }….)

Viewing 10 replies - 16 through 25 (of 25 total)
  • You must be logged in to reply to this topic.