T
T
tbalero2015-10-12 00:08:59
WordPress
tbalero, 2015-10-12 00:08:59

How to display a comment form on a custom post type page?

A custom post type has been registered on the WordPress site: movies A single-movies.php
template has been created for a separate post page of the "movies" type *A custom post type "movies" has been registered using the code (in the functions.php file):

add_action('init', 'my_custom_init');
function my_custom_init()
{
// Регистрация произвольного типа записей "movies"
$labels = array(
'name' => 'Фильмы', // Основное название типа записи
'singular_name' => 'Фильм', // отдельное название записи типа movies
'add_new' => 'Добавить новый',
'add_new_item' => 'Добавить новый Фильм',
'edit_item' => 'Редактировать Фильм',
'new_item' => 'Новый Фильм',
'view_item' => 'Посмотреть Фильм',
'search_items' => 'Найти Фильм',
'not_found' => 'Фильмов не найдено',
'not_found_in_trash' => 'В корзине Фильмов не найдено',
'parent_item_colon' => '',
'menu_name' => 'Фильмы'
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title','editor','thumbnail','excerpt','comments')
);
register_post_type('movies',$args);
// Регистрация произвольного типа записей "movies"
// end
}
// Добавляем фильтр, который изменит сообщение при публикации при изменении типа записи movies
add_filter('post_updated_messages', 'movies_updated_messages');
function movies_updated_messages( $messages ) {
global $post, $post_ID;

$messages['movies'] = array(
0 => '', // Не используется. Сообщения используются с индекса 1.
1 => sprintf( 'movies обновлено. Посмотреть запись movies', esc_url( get_permalink($post_ID) ) ),
2 => 'Произвольное поле обновлено.',
3 => 'Произвольное поле удалено.',
4 => 'Запись movies обновлена.',
/* %s: дата и время ревизии */
5 => isset($_GET['revision']) ? sprintf( 'Запись movies восстановлена из ревизии %s', wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
6 => sprintf( 'Запись movies опубликована. Перейти к записи movies', esc_url( get_permalink($post_ID) ) ),
7 => 'Запись movies сохранена.',
8 => sprintf( 'Запись movies сохранена. Предпросмотр записи movies', esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
9 => sprintf( 'Запись movies запланирована на: %1$s. Предпросмотр записи movies',
// Как форматировать даты в PHP можно посмотреть тут: php.net/date
date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
10 => sprintf( 'Черновик записи movies обновлен. Предпросмотр записи movies', esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
);

return $messages;
}

// показ раздела "помощь" для типа записей movies
add_action( 'contextual_help', 'add_help_text', 10, 3 );

function add_help_text($contextual_help, $screen_id, $screen) {
//$contextual_help .= var_dump($screen); // используйте чтобы помочь определить параметр $screen->id
if ('movies' == $screen->id ) {
$contextual_help =
'Напоминалка при редактировании записи movies:
Указать нужную информацию.
Если нужно запланировать публикацию на будущее:
В блоке с кнопкой "опубликовать" нажмите редактировать дату.
Измените дату на нужную, будущую и подтвердите изменения кнопкой ниже "ОК".
';
} elseif ( 'edit-movies' == $screen->id ) {
$contextual_help =
'Это раздел помощи, показанный для типа записи movies' ;
}
return $contextual_help;
}

In order to display the form for entering comments on the post page of an arbitrary "movies" type, we add the standard function in the single-movies.php template: As a result, on a separate page of the "movies" type post, instead of the form for entering comments, the text is displayed: * In this case, in the case of records of the standard type - when using the function - the form for entering comments is displayed correctly. *In the admin panel in the tab "Discussion settings" - the checkbox "Allow comments on new articles" is checked *The checkbox "Automatically close the discussion of articles older than 14 days" is not checked *The checkbox "Users must be registered and authorized to comment."<?php comments_template(); ?>
Обсуждение закрыто.
<?php comments_template(); ?>
*In the admin panel directly on the page for editing a record of an arbitrary type - the "Discussion" block is displayed. It has two checkboxes: "Allow comments." ; "Allow backlinks and notifications."
By default, in the checkbox "Allow comments." - the checkbox is not set.
If the checkbox is checked manually, then the form for entering comments will be displayed correctly on the post page of the arbitrary type "movies". However, the form for entering comments will be displayed only on the page of one particular post, for which the "Allow comments." checkbox was manually checked in the admin panel, and not on all pages of posts of the arbitrary "movies" type.
The question is how to make the checkbox "Allow comments." would the checkbox be checked by default for all records of the custom type "movies" ? (for the comment form to be displayed by default on custom post type pages?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Korolev, 2015-10-12
@tbalero

1) Make sure that register_post_type in the 'supports' parameter says 'comments' ( https://codex.wordpress.org/Function_Reference/reg... )
2) In the "discussion settings" tab (yes, the one about which you wrote), uncheck, save, check, save.
UPD:
3) Automatic inclusion of comments for new entries:

add_filter( 'wp_insert_post_data', 'toster256163_comments_on' );
function toster256163_comments_on( $post_data ) {
    if ( $post_data['post_type'] === 'movies' ) {
        $post_data['comment_status'] = 'open';
    }
    return $post_data;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question