钩子文档

comments_template

💡 云策文档标注

概述

comments_template 过滤器用于修改主题中评论模板文件的路径。开发者可通过此过滤器加载自定义评论模板,例如从插件中替换主题默认模板。

关键要点

  • 过滤器名称:comments_template,参数为 $theme_template(主题模板文件路径)。
  • 主要用途:允许插件或主题加载自定义评论模板文件,覆盖默认模板。
  • 返回值:过滤器函数必须返回模板文件的完整路径,否则页面可能显示空白。
  • 兼容性注意:在较新的块主题(如 Twenty Twenty-Three)中,此过滤器可能失效,需使用其他方法如 pre_render_block 过滤器处理评论块。

代码示例

function my_plugin_comment_template( $theme_template ) {
    global $post;
    if ( ! ( is_single() || is_page() || $post->comment_status ) ) {
        return;
    }
    if ( $post->post_type == 'business' ) {
        return dirname(__FILE__) . '/reviews.php';
    }
}
add_filter( "comments_template", "my_plugin_comment_template" );

注意事项

  • 过滤器函数应检查条件(如文章类型)后返回路径,否则可能影响默认行为。
  • 对于块主题,建议使用 pre_render_block 过滤器来禁用或修改评论块,例如通过检查 'core/comments' 块名。

📄 原文内容

Filters the path to the theme template file used for the comments template.

Parameters

$theme_templatestring
The path to the theme template file.

More Information

The comments_template filter can be used to load a custom template form a plugin which replaces the theme’s default comment template.

Source

$include = apply_filters( 'comments_template', $theme_template );

Changelog

Version Description
1.5.1 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Code example migrated from Codex:

    A plugin can register as a content filter with the code:

    Where my_plugin_comment_template is the function WordPress should call when the comment_template() function is called on the theme. Note that the filter function the plugin defines must return the a full path to a template file or the resulting page will be blank.

    This is an example of loading a different comments template for a custom post type:

    comment_status ) ) ) {
            return;
         }
         if($post->post_type == 'business'){ // assuming there is a post type called business
            return dirname(__FILE__) . '/reviews.php';
         }
    }
    
    add_filter( "comments_template", "my_plugin_comment_template" );
    ?>

    The example code will load the template file reviews.php located in your plugins folder for CPT called business; otherwise, the code uses default template.

  2. Skip to note 4 content

    This filter is broken/unworking on newer block themes, such as Twenty Twenty-Three.

    A replacement to i.e. disable the comments “template” (aka block) would now be:

    function wpdocs_remove_comment_template_part( $pre_render, $parsed_block ) {
        if ( 'core/comments' === $parsed_block['blockName'] ) {
            return '';
        }
    }
    add_filter('pre_render_block', 'wpdocs_remove_comment_template_part', 10, 2 );