腾讯云服务器优惠活动华纳云香港服务器

comments_template()函数如何获取不同评论模板?

WordPress主题推荐

WordPress 主题的文章页 single.php 或页面 page.php 文件一般都会通过 comments_template()函数来获取评论模板,大多数情况下都是直接使用以下代码:

<?php if ( comments_open() || get_comments_number() ) : ?>
<?php comments_template( '', true ); ?>
<?php endif; ?>

或者使用直接不带参数使用以下代码

<?php comments_template(); ?>

这种情况都是默认加载当前主题的 comments.php 评论模板文件,那么有没有办法加载不同的评论模板呢?在会回答这个问题之前我们先来了解一下 comments_template()函数吧。

comments_template()函数介绍

comments_template( string $file = '/comments.php', bool $separate_comments = false )
  • $file:(字符串)(可选)要加载的文件,默认值:’/comments.php’;
  • $separate_comments(布尔值)(可选)是否按评论类型划分评论,默认值:false。

comments_template()函数使用

在介绍使用之前回到本文开头的代码,不带参数的 comments_template()就相当于 comments_template(‘/comments.php’,false)。而大多数情况下,我们都是希望按评论类型划分评论,所以最后一个参数一般都建议为 true。所以正常获取评论模板的代码应该就是本文开头所说的:

//允许评论或有一条及以上评论时加载默认评论模板
<?php if ( comments_open() || get_comments_number() ) : ?>
<?php comments_template( '', true ); ?>
<?php endif; ?>

弄明白了 comments_template()函数的使用,那么回到本文的主题,什么情况下会用到 comments_template()函数加载不同的评论模板?比如 boke112 导航的其他文章类型是加载正常的评论模板文件,而博客目录页目前打算关闭评论的,但是以前已有评论的目录页我也打算保留这些评论内容,那么有两种办法可以做到,一个是手工去编辑目录页然后关闭评论,另一个办法就是建立一个只显示评论内容而没有评论功能的模板文件,然后在博客目录页文件中加载该评论即可。具体做法就是将当前主题的 comments.php 文件另存为另一个文件,如 bkml-comments.php,然后使用以下代码即可加载该文件:

<?php comments_template( '/bkml-comments.php', true ); ?>

本文地址:https://boke112.com/post/6788.html

赞 (0) 打赏
版权声明:本文为原创文章,版权归 boke112百科 所有,欢迎分享本文,转载请保留出处!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu