comments_template() │ WP 1.5.0 Підвантажує файл шаблону коментарів на сторінці запису: /comments.php із папки теми.
Нічого не виведе, якщо функція викликана зі сторінки відмінної від is_singular() або якщо запис немає коментарів, або коментарі закриті.
Те який HTML виведе ця функція залежить від цього, який код перебуває у файлі comments.php
.
Якщо у темі немає файлу /comments.php , то буде підключений дефолтний файл із ядра WordPress: /wp-includes/theme-compat/comments.php .
ВАЖЛИВО. Функція робить важливу операцію: отримує коментарі з бази даних і записує в глобальну змінну, щоб функція wp_list_comments() могла працювати і виводила коментарі.
Використовує глобальні змінні:
(bool) $withcomments
(WP_Query) $wp_query
(WP_Post) $post
(wpdb) $wpdb
(int) $id
(WP_Comment) $comment
(string) $user_login
(int) $user_ID
(string) $user_identity
(bool) $overridden_cpage Повертає null
.
Використання <?php comments_template( $file, $separate_comments ); ?> $file (рядок) Файл, що підключається. За замовчуванням: ‘/comments.php’ $separate_comments (логічний) Чи потрібно розділяти коментарі на кшталт (коменти, пінги, трекбеки). Типово: false Приклади #1 Базове підключення коментарів у темі <?php comments_template(); ?> #2 Підключення стороннього файлу шаблону У деяких випадках може знадобитися підключити інший файл шаблону коментарів, для цього вкажіть $file .
В даному випадку буде підключений файл: short-comments.php з каталогу теми замість comments.php :
<?php comments_template('/short-comments.php'); ?> Якщо потрібно підключити файл із папки теми, то вказуємо шлях до файлу щодо папки теми:
<?php comments_template( '/templates/my-comments.php' ); ?> #3 Зміна шляху до файлу через фільтр add_filter( 'comments_template', 'my_plugin_comment_template' ); function my_plugin_comment_template( $comment_template ){ global $post; if ( !( is_singular() && ( have_comments() || 'open' == $post->comment_status ) ) ) { return; } // якщо це потрібний тип запису book if( $post->post_type == 'book' ){ return __DIR__ . '/reviews.php'; // Повний шлях до файлу } } Додати свій приклад
нотатки Global. WP_Query. $wp_query WordPress Query object. Global. WP_Post. $post Global post об’єкт. Global. wpdb. $wpdb WordPress database abstraction object. Global. int. $id Global. WP_Comment. $comment Global comment object. Global. Рядок. $user_login Global. Рядок. $user_identity Global. true | false. $overridden_cpage Global. true | false. $withcomments список змін Код comments_template() comments template WP 6.0.2 function comments_template( $file = '/comments.php', $separate_comments = false ) { Global $wp_query, $withcomments, $post, $wpdb, $id, $comment, $user_login, $user_identity, $overridden_cpage; if ( ! ( is_single() || is_page() || $withcomments ) || empty( $post ) ) { return; } if (empty($file)) { $file = '/comments.php'; } $req = get_option( 'require_name_email'); /* * Comment author information зроблено з comment cookies. */ $commenter = wp_get_current_commenter(); /* * Назвою поточного коментаря автора escaped for use in attributes. * Escaped by sanitize_comment_cookies(). */ $comment_author = $commenter['comment_author']; /* * Електронна адреса поточного коментаря автора escaped for use in attributes. * Escaped by sanitize_comment_cookies(). */ $comment_author_email = $commenter['comment_author_email']; /* * URL з поточного коментаря автора escaped for use in attributes. */ $comment_author_url = esc_url( $commenter['comment_author_url'] ); $comment_args = array( 'orderby' => 'comment_date_gmt', 'order' => 'ASC', 'status' => 'approve', 'post_id' => $post->ID, 'no_found_rows' => false, 'update_comment_meta_cache' => false, // We lazy-load comment meta for performance. ); if ( get_option( 'thread_comments' ) ) { $comment_args['hierarchical'] = 'threaded'; } else { $comment_args['hierarchical'] = false; } if ( is_user_logged_in() ) { $comment_args['include_unapproved'] = array( get_current_user_id() ); } else { $unapproved_email = wp_get_unapproved_comment_author_email(); if ( $unapproved_email ) { $comment_args['include_unapproved'] = array( $unapproved_email ); } } $per_page = 0; if ( get_option( 'page_comments' ) ) { $per_page = (int) get_query_var( 'comments_per_page' ); if ( 0 === $per_page ) { $per_page = (int) get_option( 'comments_per_page' ); } $comment_args['number'] = $per_page; $page = (int) get_query_var( cpage ); if ($page) { $comment_args['offset'] = ($page - 1) * $per_page; } elseif ( 'oldest' === get_option( 'default_comments_page' ) ) { $comment_args['offset'] = 0; } else { // Якщо вивчається перша сторінка 'невести', ми потребуємо top-level comment count. $top_level_query = новий WP_Comment_Query(); $top_level_args = array( 'count' => true, 'orderby' => false, 'post_id' => $post->ID, 'status' => 'approve', ); if ( $comment_args['hierarchical'] ) { $top_level_args['parent'] = 0; } if ( isset( $comment_args['include_unapproved'] ) ) { $top_level_args['include_unapproved'] = $comment_args['include_unapproved']; } /** * Filters the arguments used в top level comments query. * * @ Since 5.6.0 * * @see WP_Comment_Query::__construct() * * @param array $top_level_args { * top level query arguments for comments template. * * @type bool $count Whether to return a comment count. * @type string|array $orderby Поле(s) to order by. * @type int $post_id The post ID. * @type string|array $status Коментарі до статуя до граничних результатів. * } */ $top_level_args = apply_filters( 'comments_template_top_level_query_args', $top_level_args ); $top_level_count = $top_level_query->query( $top_level_args ); $comment_args['offset'] = (ceil($top_level_count / $per_page) - 1) * $per_page; } } /** * Filters the arguments use to query comments in comments_template(). * * @ Since 4.5.0 * * @see WP_Comment_Query::__construct() * * @param array $comment_args { * Array of WP_Comment_Query arguments. * * @type string|array $orderby Field(s) to order by. * @type string $order Order of results. Accepts 'ASC' або 'DESC'. * @type string $status Comment status. * @type array $include_unapproved Array of IDs або email address whose unapproved comments * will be included in results. * @type int $post_id ID of the post. * @type bool $no_found_rows Whether to refrain from querying for found rows. * @type bool $update_comment_meta_cache Whether to prime cache for comment meta. * @type bool|string $hierarchical Whether to query for comments hierarchically. * @type int $offset Comment offset. * @type int $number Кількість коментарів до fetch. * } */ $comment_args = apply_filters( 'comments_template_query_args', $comment_args ); $comment_query = новий WP_Comment_Query( $comment_args ); $_comments = $comment_query->comments; // Trees must be flattened before they're passed to the walker. if ( $comment_args['hierarchical'] ) { $comments_flat = array(); foreach ( $_comments as $_comment ) { $comments_flat[] = $_comment; $comment_children = $_comment->get_children( array( 'format' => 'flat', 'status' => $comment_args['status'], 'orderby' => $comment_args['orderby'], ) ); foreach ( $comment_children as $comment_child ) { $comments_flat[] = $comment_child; } } } else { $comments_flat = $_comments; } /** * Filters the comments array. * * @ Since 2.1.0 * * @param array $comments Повідомити про коментарі supplied to the comments template. * @param int $post_ID Post ID. */ $wp_query->comments = apply_filters( 'comments_array', $comments_flat, $post->ID ); $comments = &$wp_query->comments; $wp_query->comment_count = count( $wp_query->comments ); $wp_query->max_num_comment_pages = $comment_query->max_num_pages; if ( $separate_comments ) { $wp_query->comments_by_type = separate_comments( $comments ); $comments_by_type = &$wp_query->comments_by_type; } else { $wp_query->comments_by_type = array(); } $overridden_cpage = false; if ( '' == get_query_var( 'cpage' ) && $wp_query->max_num_comment_pages > 1 ) { set_query_var( 'cpage', 'newest' === get_option( 'default_comments_page' ) ? get_comment_pages_count() : 1 ); $overridden_cpage = true; } if ( ! defined( 'COMMENTS_TEMPLATE' ) ) { define( 'COMMENTS_TEMPLATE', true ); } $theme_template = STYLESHEETPATH . $ file; /** * Filters the path to thetem template file used for the comments template. * * @ Since 1.5.1 * * @param string $theme_template Тест до теми Template file. */ $include = apply_filters( 'comments_template', $theme_template ); if ( file_exists( $include ) ) { require $include; } elseif ( file_exists ( TEMPLATEPATH . $ file ) ) { require TEMPLATEPATH. $ file; } else { // Backward compat code will be removed in future release. require ABSPATH. WPINC. '/theme-compat/comments.php'; } } Зв’язані функції