WordPress 修改密码保护文章的评论链接文字
WordPress 的 comments_popup_link()
函数输出指向文章评论内容的链接,链接文字为评论条数。如首页和文章页中的 7 条评论,或者发表评论。
我们可以通过参数来控制文字内容,例如官方给出的示例:
<?php comments_popup_link( 'No comments yet', '1 comment', '% comments', 'comments-link', 'Comments are off for this post'); ?>
则链接文字在无评论时显示“No comments yet”,一条评论时显示“1 comment”,多条评论时显示“% comments”,其中“%”代表具体评论数量。后面两个参数与本文无关:“comments-link”定义的是给链接 a 标签内添加 class 属性的值;“Comments are off for this post”为当文章关闭评论时显示的文字内容,不过我测试了下这个参数在官方的 twentysixteen 和目前使用的主题上都无效,题外话。
而对于添加了密码保护的文章,链接文字就变成了“Enter your password to view comments.”由于英文比较长,导致目前主题在登录了用户并使用手机浏览文章页的情况下,这段文字与快捷进入后台编辑文章的 [ 编辑 ] 按钮相碰撞使得版面错位。而无密码的文章显示文字较短,排版就没有问题。因此打算替换这段文字为简短的汉字。通过搜索找到两个方法,这里记录一下。
一、判断文章是否有密码保护,输出相应内容
在 comments_popup_link()
处加入判断,当文章无密码保护时输出评论数链接,否则输出自定义文字。修改主题文件,将原
<?php comments_popup_link( '发表评论', '1 条评论', '% 条评论' ); ?>
代码替换为:
<?php if ( ! post_password_required() ) { comments_popup_link( '发表评论', '1 条评论', '% 条评论' ); } else { echo '输入密码查看评论'; } ?>
或者直接把上面代码封装为新的函数,在主题 functions.php 中添加代码:
<?php function custom_comments_popup_link() { if ( ! post_password_required() ) { comments_popup_link( '发表评论', '1 条评论', '% 条评论' ); } else { echo '输入密码查看评论'; } } ?>
再将主题文件中输出评论链接的函数 comments_popup_link()
替换为 custom_comments_popup_link()
,调用这个新函数就可以了。
二、使用过滤器替换密码保护文章的链接文字
在主题 functions.php 中添加代码即可:
<?php function custom_comment_num_text( $translation, $text, $domain ) { if ( 'Enter your password to view comments.' === $text && 'default' === $domain ) { $translation = '输入密码查看评论'; } return $translation; } function gettext_switch_filter() { $do_filter = 'loop_start' === current_filter() ? 'add_filter' : 'remove_filter'; $do_filter( 'gettext', 'custom_comment_num_text', 10, 3 ); } add_action( 'loop_start', 'gettext_switch_filter' ); add_action( 'loop_end', 'gettext_switch_filter' ); ?>
文字的内容可以通过修改第四行单引号内的“输入密码查看评论”自定义。这种方法比较简便,不需要改动现有的含有 comments_popup_link()
函数的主题文件,一劳永逸。该方法取自:Comments number message in password protected post – WordPress Development Stack Exchange。
快来发表评论吧!