comment_form() WP 3.0.0

Виводить на екран готовий код форми коментування.

Більшість полів форми можна змінити за допомогою параметрів функції або через фільтр comment_form_default_fields .

Також є можливість вставляти поля (кожен окремо) через фільтр comment_form_field_$name , де $name ключ, який використовується в масиві полів.

Повертає

null.

Використання

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 в цьому браузері для подальшого часу 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 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( __( 'Ви можете використовувати ці <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)
Атрибут клас для форми коментування.


За замовчуванням: ‘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’ )

class_container
(рядок) (WP 5.5)
атрибут для контейнера форми.


За замовчуванням: ‘comment-respond’

Приклади

0

#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 в цьому браузері для подальшого часу 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 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_container' => 'comment-respond',
	'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);
0

#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);
0

#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.0Introduced the ‘class_submit’ argument.
З версії 4.2.0Introduced the ‘submit_button’ and ‘submit_fields’ arguments.
З версії 4.4.0Introduced the ‘class_form’ , ‘title_reply_before’ , ‘title_reply_after’ , ‘cancel_reply_before’ , and ‘cancel_reply_after’ arguments.
З версії 4.5.0The ‘author’ , ’email’ , і ‘url’ form fields є обмеженими до 245, 100, and 200 characters, respectively.
З версії 4.6.0Introduced the ‘action’ argument.
З версії 4.9.6Introduced the ‘cookies’ default comment field.
З версії 5.5.0Introduced the ‘class_container’ argument.

comment form WP 6.0.2

<?php function comment_form( $args = array(), $post_id = null ) { if ( null === $post_id ) { $post_id = get_the_ID(); } // Exit the function when comments for the post are closed. if ( ! comments_open( $post_id ) ) { /** * Fires after the comment form if comments are closed. * * @ Since 3.0.0 */ do_action( 'comment_form_comments_closed'); return; } $commenter = wp_get_current_commenter(); $user = wp_get_current_user(); $user_identity = $user->exists() ? $user->display_name : ''; $ args = wp_parse_args ($ args); if ( ! isset( $args['format'] ) ) { $args['format'] = current_theme_supports( 'html5', 'comment-form' ) ? 'html5' : 'xhtml'; } $req = get_option( 'require_name_email'); $html5 = 'html5' === $args['format']; // Define attributes в HTML5 або XHTML syntax. $required_attribute = ( $html5 ? 'required' : 'required="required"' ); $checked_attribute = ( $html5 ? 'checked' : 'checked="checked"'); // Identify required fields visually. $required_indicator = ' <span class="required" aria-hidden="true">*</span>'; $fields = array( 'author' => sprintf( '<p class="comment-form-author">%s %s</p>', sprintf( '<label for="author">%s%s</label>', __( 'Name' ), ( $req ? $required_indicator : '' ) ), sprintf( '<input id="author" name="author" type="text" value="%s" size="30" maxlength="245"%s />', esc_attr( $commenter['comment_author'] ), ( $req ? $required_attribute : '' ) ) ), 'email' => sprintf( '<p class="comment-form-email">%s %s</p>', sprintf( '<label for="email">%s%s</label>', __( 'Email' ), ( $req ? $required_indicator : '' ) ), sprintf( '<input id="email" name="email" %s value="%s" size="30" maxlength="100" aria-describedby="email-notes"%s />', ( $html5 ? 'type="email"' : 'type="text"' ), esc_attr( $commenter['comment_author_email'] ), ( $req ? $required_attribute : '' ) ) ), 'url' => sprintf( '<p class="comment-form-url">%s %s</p>', sprintf( '<label for="url">%s</label>', __( 'Website' ) ), sprintf( '<input id="url" name="url" %s value="%s" size="30" maxlength="200" />', ( $html5 ? 'type="url"' : 'type="text"' ), esc_attr( $commenter['comment_author_url'] ) ) ), ); if ( has_action( 'set_comment_cookies', 'wp_set_comment_cookies' ) && get_option( 'show_comments_cookies_opt_in' ) ) { $consent = empty( $commenter['comment_author_email'] ) ? '' : $checked_attribute; $fields['cookies'] = sprintf( '<p class="comment-form-cookies-consent">%s %s</p>', sprintf( '<input id="wp-comment-cookies-consent" name="wp-comment-cookies-consent" type="checkbox" value="yes"%s />', $consent ), sprintf( '<label for="wp-comment-cookies-consent">%s</label>', __( 'Save my name, email, and website в цьому браузері для next time I comment.' ) ) ); // Ensure that the passed fields включає cookies consent. if ( isset( $args['fields'] ) && ! isset( $args['fields']['cookies'] ) ) { $args['fields']['cookies'] = $fields['cookies']; } } $required_text = sprintf( /* translators: %s: Asterisk symbol (*). */ ' <span class="required-field-message" aria-hidden="true">' . __( 'Required fields are marked %s' ) . '</span>', trim( $required_indicator ) ); /** * Filters default comment form fields. * * @ Since 3.0.0 * * @param string[] $fields Array of the default comment fields. */ $fields = apply_filters( 'comment_form_default_fields', $fields ); $defaults = array( 'fields' => $fields, 'comment_field' => sprintf( '<p class="comment-form-comment">%s%s</p>', sprintf( '<label for="comment">%s%s</label>', _x( 'Comment', 'noun' ), $required_indicator ), '<textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525"' . $required_attribute . '></textarea>' ), 'must_log_in' => sprintf( '<p class="must-log-in">%s</p>', sprintf( /* translators: %s: Login URL. */ __( 'You must be <a href="%s">logged in</a> to post a comment.' ), /** Цей filter is documented в wp-includes/link-template.php */ wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ), $post_id ) ) ) ), 'logged_in_as' => sprintf( '<p class="logged-in-as">%s%s</p>', sprintf( /* translators: 1: Edit user link, 2: Accessibility text, 3: User name, 4: Logout URL. */ __( '<a href="%1$s" aria-label="%2$s">Logged in as %3$s</a>. <a href="%4$s">Log out? </a>' ), get_edit_user_link(), /* translators: %s: User name. */ esc_attr( sprintf( __( 'Logged in as %s. Edit your profile.' ), $user_identity ) ), $user_identity, /** Цей filter is documented в wp-includes/link-template.php */ wp_logout_url( apply_filters( 'the_permalink', get_permalink( $post_id ), $post_id ) ) ), $required_text ), 'comment_notes_before' => sprintf( '<p class="comment-notes">%s%s</p>', sprintf( '<span id="email-notes">%s</span>', __( 'Your email address will not be published.' ) ), $required_text ), 'comment_notes_after' => '', 'action' => site_url( '/wp-comments-post.php' ), 'id_form' => 'commentform', 'id_submit' => 'submit', 'class_container' => 'comment-respond', 'class_form' => 'comment-form', 'class_submit' => 'submit', 'name_submit' => 'submit', 'title_reply' => __( 'Leave a Reply' ), /* translators: %s: Author of the comment being replied to. */ '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', ); /** * Filters the comment form default arguments. * * Use {@see 'comment_form_default_fields'} до filter the comment fields. * * @ Since 3.0.0 * * @param array $defaults Додаткові коментарі form arguments. */ $args = wp_parse_args( $args, apply_filters( 'comment_form_defaults', $defaults ) ); // Ensure that the filtered arguments contain all required default values. $ args = array_merge ($ defaults, $ args); // Remove 'aria-describedby' від електронної пошти, якщо не є поєднаним описом. if ( isset( $args['fields']['email'] ) && false === strpos( $args['comment_notes_before'], 'id="email-notes"' ) ) { $args['fields']['email'] = str_replace( ' aria-describedby="email-notes"', '', $args['fields']['email'] ); } /** * Fires before the comment form. * * @ Since 3.0.0 */ do_action( 'comment_form_before'); ?> <div id="respond" class="<?php echo esc_attr( $args['class_container'] ); ?>"> <?php echo $args['title_reply_before']; comment_form_title( $args['title_reply'], $args['title_reply_to'] ); if ( get_option( 'thread_comments' ) ) { echo $args['cancel_reply_before']; cancel_comment_reply_link( $args['cancel_reply_link'] ); echo $args['cancel_reply_after']; } echo $args['title_reply_after']; if ( get_option( 'comment_registration' ) && ! is_user_logged_in() ) : echo $args['must_log_in']; /** * Fires after the HTML-форматований 'must log in after' message in the comment form. * * @ Since 3.0.0 */ do_action( 'comment_form_must_log_in_after'); else : printf( '<form action="%s" method="post" id="%s" class="%s"%s>', esc_url( $args['action'] ), esc_attr( $args['id_form'] ), esc_attr( $args['class_form'] ), ( $html5 ? ' novalidate' : '' ) ); /** * Fires at the top of comment form, inside the form tag. * * @ Since 3.0.0 */ do_action( 'comment_form_top'); if ( is_user_logged_in() ) : /** * Filters 'logged in' message for comment form for display. * * @ Since 3.0.0 * * @param string $args_logged_in The logged-in-as HTML-formatted message. * @param array $commenter An array розміщення коментаря автора * username, email, and URL. * @param string $user_identity Якщо електронна пошта є registered user, * Display name, blank otherwise. */ echo apply_filters( 'comment_form_logged_in', $args['logged_in_as'], $commenter, $user_identity ); /** * Fires after the is_user_logged_in() check in the comment form. * * @ Since 3.0.0 * * @param array $commenter An array розміщення коментаря автора * username, email, and URL. * @param string $user_identity Якщо електронна пошта є registered user, * Display name, blank otherwise. */ do_action( 'comment_form_logged_in_after', $commenter, $user_identity ); else : echo $args['comment_notes_before']; endif; / / Prepare array of all fields, включаючи textarea. $comment_fields = array( 'comment' => $args['comment_field'] ) + (array) $args['fields']; /** * Filters comment form fields, включаючи textarea. * * @ Since 4.4.0 * * @param array $comment_fields The comment fields. */ $comment_fields = apply_filters( 'comment_form_fields', $comment_fields ); // Get an array of field names, виключаючи textarea. $comment_field_keys = array_diff( array_keys( $comment_fields ), array( 'comment' ) ); // Get the first and the last field name, excluding the textarea. $first_field = reset( $comment_field_keys ); $last_field = end ($ comment_field_keys); foreach ( $comment_fields as $name => $field ) { if ( 'comment' === $name ) { /** * Filters content of the comment textarea field for display. * * @ Since 3.0.0 * * @param string $args_comment_field Створення вмісту повідомлень текстової області. */ echo apply_filters( 'comment_form_field_comment', $field ); echo $args['comment_notes_after']; } elseif ( ! is_user_logged_in() ) { if ( $first_field === $name ) { /** * Fires before comment fields in the comment form, excluding the textarea. * * @ Since 3.0.0 */ do_action( 'comment_form_before_fields'); } /** * Filters a comment form field for display. * * The dynamic portion of the hook name, `$name`, refers to the name * of the comment form field. * * Possible hook names include: * * - `comment_form_field_comment` * - `comment_form_field_author` * - `comment_form_field_email` * - `comment_form_field_url` * - `comment_form_field_cookies` * * @ Since 3.0.0 * * @param string $field У HTML-форматованому повідомленні повідомлень про повідомлення. */ echo apply_filters( "comment_form_field_{$name}", $field ) . "n"; if ( $last_field === $name ) { /** * Fires after the comment fields в comment form, виключаючи the textarea. * * @ Since 3.0.0 */ do_action( 'comment_form_after_fields'); } } } $submit_button = sprintf( $args['submit_button'], esc_attr( $args['name_submit'] ), esc_attr( $args['id_submit'] ), esc_attr( $args['class_submit'] ), esc_attr( $args['label_submit'] ) ); /** * Filters submit button for comment form to display. * * @ Since 4.2.0 * * @param string $submit_button HTML markup for the submit button. * @param array $args Arguments passed to comment_form(). */ $submit_button = apply_filters( 'comment_form_submit_button', $submit_button, $args ); $submit_field = sprintf( $args['submit_field'], $submit_button, get_comment_id_fields( $post_id ) ); /** * Filters the submit field for comment form to display. * * The submit field включають submit button, hidden fields for the * comment form, and any wrapper markup. * * @ Since 4.2.0 * * @param string $submit_field HTML markup for the submit field. * @param array $args Arguments passed to comment_form(). */ echo apply_filters( 'comment_form_submit_field', $submit_field, $args ); /** * Fires at the bottom of comment form, inside the closing form tag. * * @ Since 1.5.0 * * @param int $post_id The post ID. */ do_action( 'comment_form', $post_id ); echo '</form>'; endif; ?> </div><!-- #respond --> <?php /** * Fires after the comment form. * * @ Since 3.0.0 */ do_action( 'comment_form_after'); }

Залишити відповідь

Ваша e-mail адреса не оприлюднюватиметься. Обов’язкові поля позначені *