comment_form() WP 3.0.0
Выводит на экран готовый код формы комментирования, который можно использовать в шаблонах.
Большинство полей формы можно изменить через параметр $args или можно использовать фильтр comment_form_default_fields чтобы изменить параметры по умолчанию, например, если нужно добавить новое поле или удалить существующее.
Также есть возможность вставлять поля (каждое в отдельности) через фильтр comment_form_field_$name, где $name ключ, который используется в массиве полей.
Хуки из функции
Использование
comment_form( $args, $post_id );
- $args(массив)
- Аргументы, в соответствии с которыми будет создана форма комментирования.
По умолчанию: предустановленные - $post_id(строка/массив/число)
- ID поста, для которого нужно вывести форму комментирования.
По умолчанию: null (текущий пост)
Аргументы параметра $args
- action(строка) (WP 4.6)
- Значение атрибута action формы.
По умолчанию: site_url('/wp-comments-post.php') - fields(массив)
Поля ввода данных:
author
,email
,url
.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 . $html_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-describedby="email-notes"' . $aria_req . $html_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>', 'cookies' => '<p class="comment-form-cookies-consent">'. sprintf( '<input id="wp-comment-cookies-consent" name="wp-comment-cookies-consent" type="checkbox" value="yes"%s />', $consent ) .' <label for="wp-comment-cookies-consent">'. __( 'Save my name, email, and website in this browser for the next time I comment.' ) .'</label> </p>', );
Заметка: Чтобы использовать переменную $commenter в своей, произвольной функции вывода, нужно заранее определить эту переменную. Делается это так:
$commenter = wp_get_current_commenter();
По умолчанию: 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>'
- 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>' ), admin_url( 'profile.php' ), $user_identity, wp_logout_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>'
- comment_notes_before(строка)
Текст или html код, который будет показан перед полями ввода данных для не авторизированых пользователей. По умолчанию:
'<p class="comment-notes">' . __( 'Your email address will not be published.' ) . ( $req ? $required_text : '' ) . '</p>'
- comment_notes_after(строка)
Текст или html код, который будет показан после полей ввода, но до кнопки отправки комментария. По умолчанию:
'<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(строка)
- Значение атрибута id у тега
<form>
.
По умолчанию: "commentform" - class_form(строка) (WP 4.4)
- Атрибут class для формы комментирования.
По умолчанию: 'comment-form' - id_submit(строка)
- Значение атрибута id у кнопки отправки комментария (submit).
По умолчанию: 'submit' - title_reply(строка)
- Заголовок формы комментирования (когда комментируется статья) (см. comment_form_title()). По умолчанию: "Оставить комментарий".
По умолчанию: __( 'Leave a Reply' ) - title_reply_before(строка) (WP 4.4)
- HTML код перед заголовком для формы.
По умолчанию: '<h3 id="reply-title" class="comment-reply-title">' - title_reply_after(строка) (WP 4.4)
- HTML код после заголовка для формы.
По умолчанию: '</h3>' - title_reply_to(строка)
- Заголовок формы комментирования (когда комментатор отвечает на другой комментарий) (см. comment_form_title()). По умолчанию: "Ответить на комментарий: Имя комментатора".
По умолчанию: __( 'Leave a Reply to %s' ) - label_submit(строка)
- Текст кнопки отправки комментария. По умолчанию: "Оставить комментарий".
По умолчанию: __( 'Post Comment' ) - class_submit(строка) (WP 4.1)
- Атрибут class для кнопки сабмита.
По умолчанию: 'submit' - submit_button(строка) (WP 4.2)
- HTML формат кнопки сабмита.
По умолчанию: '<input name="%1$s" type="submit" id="%2$s" class="%3$s" value="%4$s" />' - submit_field(строка)
- HTML формат который окружает кнопку сабмита, а также скрытые поля. В переданном формате %1$s замениться кнопкой сабмита, а %2$s скрытыми полями.
По умолчанию: '<p class="form-submit">%1$s %2$s</p>' - cancel_reply_before(строка) (WP 4.4)
- HTML код перед ссылкой на отмену ответа на комментарий.
По умолчанию: ' <small>' - cancel_reply_after(строка) (WP 4.4)
- HTML код после ссылки на отмену ответа на комментарий.
По умолчанию: '</small>' - cancel_reply_link(строка)
- Текст ссылки "Отменить ответ".
По умолчанию: __( 'Cancel reply' ) - class_container(строка) (WP 5.5)
- class атрибут для контейнера формы.
По умолчанию: 'comment-respond'
Примеры
#1 Все параметры по-умолчанию
$defaults = [ 'fields' => [ '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 . $html_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-describedby="email-notes"' . $aria_req . $html_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>', 'cookies' => '<p class="comment-form-cookies-consent">'. sprintf( '<input id="wp-comment-cookies-consent" name="wp-comment-cookies-consent" type="checkbox" value="yes"%s />', $consent ) .' <label for="wp-comment-cookies-consent">'. __( 'Save my name, email, and website in this browser for the next time I comment.' ) .'</label> </p>', ], '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" required="required"></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( __( '<a href="%1$s" aria-label="Logged in as %2$s. Edit your profile.">Logged in as %2$s</a>. <a href="%3$s">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"> <span id="email-notes">' . __( 'Your email address will not be published.' ) . '</span>'. ( $req ? $required_text : '' ) . ' </p>', 'comment_notes_after' => '', 'id_form' => 'commentform', 'id_submit' => 'submit', 'class_form' => 'comment-form', 'class_submit' => 'submit', 'name_submit' => 'submit', 'title_reply' => __( 'Leave a Reply' ), 'title_reply_to' => __( 'Leave a Reply to %s' ), 'title_reply_before' => '<h3 id="reply-title" class="comment-reply-title">', 'title_reply_after' => '</h3>', 'cancel_reply_before' => ' <small>', 'cancel_reply_after' => '</small>', 'cancel_reply_link' => __( 'Cancel reply' ), 'label_submit' => __( 'Post Comment' ), 'submit_button' => '<input name="%1$s" type="submit" id="%2$s" class="%3$s" value="%4$s" />', 'submit_field' => '<p class="form-submit">%1$s %2$s</p>', 'format' => 'xhtml', ]; comment_form( $defaults );
#2 Изменим некоторые поля формы комментирования
$comments_args = array( // изменим название кнопки 'label_submit' => 'Отправить', // заголовок секции ответа 'title_reply'=>'Write a Reply or Comment', // удалим текст, который будет показано после того как коммент отправлен 'comment_notes_after' => '', // переопределим textarea (тело формы) 'comment_field' => '<p class="comment-form-comment"><label for="comment">' . _x( 'Comment', 'noun' ) . '</label><br /><textarea id="comment" name="comment" aria-required="true"></textarea></p>', ); comment_form( $comments_args );
#3 Изменить порядок вывода полей
Перед выводом полей их можно изменить через фильтр 'comment_form_fields' там же можно изменить порядок, т.е. чтобы textarea выводилось после полей имя, email, url. Делается это так:
add_filter('comment_form_fields', 'kama_reorder_comment_fields' ); function kama_reorder_comment_fields( $fields ){ // die(print_r( $fields )); // посмотрим какие поля есть $new_fields = array(); // сюда соберем поля в новом порядке $myorder = array('author','email','url','comment'); // нужный порядок foreach( $myorder as $key ){ $new_fields[ $key ] = $fields[ $key ]; unset( $fields[ $key ] ); } // если остались еще какие-то поля добавим их в конец if( $fields ) foreach( $fields as $key => $val ) $new_fields[ $key ] = $val; return $new_fields; }
Добавлять код можно в functions.php. Но лучше добавить прямо перед вызовом функции comment_form()
Список изменений
С версии 3.0.0 | Введена. |
С версии 4.1.0 | Introduced the 'class_submit' argument. |
С версии 4.2.0 | Introduced the 'submit_button' and 'submit_fields' arguments. |
С версии 4.4.0 | Introduced the 'class_form', 'title_reply_before', 'title_reply_after', 'cancel_reply_before', and 'cancel_reply_after' arguments. |
С версии 4.5.0 | The 'author', 'email', and 'url' form fields are limited to 245, 100, and 200 characters, respectively. |
С версии 4.6.0 | Introduced the 'action' argument. |
С версии 4.9.6 | Introduced the 'cookies' default comment field. |
С версии 5.5.0 | Introduced the 'class_container' argument. |