How to tweak comment fields properly from functions.php

With the latest version of WordPress, I’m working in my child theme. I have enabled comments on a specific page. I can see OOTB I have author, email, website and comments input areas enabled.

From my functions.php location. I would like to only hide my website field, and change the label of the comments field, from “comment” to “Leave a Review”. I have tried the following below, but its hiding everything except the textarea box for “Leave a Review. How can I also bring Author, Email, and Cookie input fields back?

function _ac_comment_fields_custom_order( $fields ) {

    $comment_field = $fields['comment'];
    $author_field = $fields['author'];
    $email_field = $fields['email'];
    $url_field = $fields['url'];
    $cookies_field = $fields['cookies'];

    unset( $fields['comment'] );
    unset( $fields['author'] );
    unset( $fields['email'] );
    unset( $fields['url'] );
    unset( $fields['cookies'] );
   
    $fields['author'] = $author_field;
    $fields['email'] = $email_field;  
    $fields = [ 
        'comment_field' => sprintf(
        '<p class="comment-form-comment">%s %s</p>',
        sprintf(
            '<label for="comment">%s</label>',
            _x( 'Your Review', 'noun' )
        ),
        '<textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" required="required"></textarea>'
    )];

    $fields['cookies'] = $cookies_field;
    
    // done ordering, now return the fields:
    return $fields;
}
add_filter( 'comment_form_fields', '_ac_comment_fields_custom_order' );

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You are redeclaring the variable $fields after you define the email key – this basically removes all previous values – instead you need to add a new key for comment_field, for example:

    // retain code before..

    $fields['author'] = $author_field;
    $fields['email'] = $email_field;  
    $fields['comment_field'] = sprintf(
        '<p class="comment-form-comment"><label for="comment">%s</label><textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" required="required"></textarea></p>',            
        __( 'Your Review', 'theme-textdomain' )
   );

    $fields['cookies'] = $cookies_field;

    // retain code after..

I also reduced your sprintf to one single function, as you only need to use this once, you should also use your own text-domain.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x