Using WordPress ‘comments_template()’ PHP function

The comments_template() WordPress PHP function loads the specified comment template. It will not display the comments template if it’s not on a single post or page, or if the post does not have comments. The function uses the WordPress database object to query for the comments and passes them through the ‘comments_array’ filter hook. The function also attempts to load the specified file, and if it fails, defaults to the comment template from the default theme.

Usage

comments_template('/my_comments.php', true);

In this example, the function will try to load the ‘my_comments.php’ file from the theme directory. If the file does not exist, it will use the default ‘comments.php’ file from the default theme. The second parameter set to ‘true’ means the comments will be separated by their type.

Parameters

  • $file (string – optional) – The file to load. Default is ‘/comments.php’.
  • $separate_comments (bool – optional) – Whether to separate the comments by comment type. Default is false.

More information

See WordPress Developer Resources: comments_template()
Note: It’s advised not to delete the default theme as this function could halt the WordPress process if it fails to find the comments template.

Examples

Basic usage

The simplest way to use the function. It will load the default comments template.

comments_template();

Custom comments template

This will load ‘custom_comments.php’ from the theme directory.

comments_template('/custom_comments.php');

Separating comments by type

This will load the default comments template, but will separate comments by type.

comments_template('/comments.php', true);

Comments template from a subfolder

This will load ‘special_comments.php’ from a subfolder in the theme directory.

comments_template('/subfolder/special_comments.php');

Only load comments template if comments are open or exist

This will load the default comments template only if comments are open or at least one comment exists.

if ( comments_open() || get_comments_number() ) {
    comments_template();
}