Function and usage of comments_template() in wordpress


Answers ( 1 )


    The comments_template() function in WordPress is an essential tool for theme developers. It's primarily used to load the comment template specified in the $file parameter.


    comments_template( string $file = '/comments.php', bool $separate_comments = false )


    • $file (string, optional): Specifies the path to the comment template file. The default value is '/comments.php'. This file is typically located within the theme's directory.
    • $separate_comments (bool, optional): Determines whether to separate comments by type (e.g., regular comments, pingbacks, trackbacks). The default value is false, which means all comment types are displayed together.

    Description and Behavior:

    1. Template Loading: The function attempts to load the comment template file specified by $file. If $file is not provided, it defaults to loading '/comments.php' from the current theme.

    2. Context Check: It only displays the comments template if the current page is a single post or page, and the post has comments.

    3. Comments Query: Utilizes the WordPress database object to retrieve comments for the post. These comments are then passed through the comments_array filter hook, along with the post ID.

    4. Filter Hook: The $file path is processed through the comments_template filter hook. This hook combines the template directory path and $file. The function first tries to load the template from the filtered path. If this fails, it defaults to the standard comments template from the default theme.

    5. Error Handling: If neither the custom nor the default comment template exists, WordPress halts execution. This behavior underscores the importance of not deleting the default theme, as it serves as a fallback.

    6. Comments Check: The function does not attempt to load comments if the post has none.

    Sample Usage:

    In a WordPress theme, you might find the comments_template() function used within the single post template (single.php) like this:

    if ( is_single() ) {
        // Load comments template with default settings

    Or, if you want to use a custom comments file and separate comments by type:

    // Load a custom comments template and separate comments by type
    comments_template( '/custom-comments.php', true );

    This function is integral to WordPress themes, enabling a dynamic and interactive commenting experience. It leverages WordPress's hooks and filters, ensuring a customizable and extendable commenting system.

Leave an answer