新方法修复WordPress 5.1评论回复失效

编辑于:2019年04月28日

新方法修复WordPress 5.1评论回复失效

自从升级至WordPress 5.1,玩机APP网站的评论回复功能便失效了:点击回复按钮不弹出评论框。张戈、知更鸟等网上流传的方法,对我使用的乐趣公园Git主题并没有效果,今天终于发现了一种有效的解决方案。

回复失效原因

WordPress 5.1更改了的wp-includes/comment-template.php文件的get_comment_reply_link()函数,5.0及以前的版本,该函数输出评论回复链接按钮是绑定有一个onclick, 5.1版本之后没有了这个onclick。

//5.0以前的代码
$onclick = sprintf( 'return addComment.moveForm( "%1$s-%2$s", "%2$s", "%3$s", "%4$s" )',
$args['add_below'], $comment->comment_ID, $args['respond_id'], $post->ID
);

常规解决办法

方法一

网上流传最广的方法是张戈博客分享的方法,在functions文件里加入如下代码,将WordPress的评论JS文件加载到前台页面。

<?php if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { ?>
<script type='text/javascript' src='/wp-includes/js/comment-reply.min.js?ver=5.1.1'></script>
<?php } ?>

方法二

很遗憾方法一对我所用的乐趣公园Git主题并没有效果,主题作者云落也没更新主题解决该问题,所以玩机APP一直处于无法评论回复状态。

今天虫子菌又在网上查找WordPress 5.1评论回复功能失效问题,在后宫学长看了一个来自俄罗斯网站分享办法,经过测试,如上图,评论回复框能够正常显示了。

//修复评论回复功能失效
global $wp_version;
if (version_compare($wp_version, '5.1.1', '>=')) {
    add_filter('comment_reply_link', 'haremu_replace_comment_reply_link', 10, 4);
    function haremu_replace_comment_reply_link($link, $args, $comment, $post)
    {
        if (get_option('comment_registration') && !is_user_logged_in()) {
            $link = sprintf(
                '<a rel="nofollow" class="comment-reply-login" href="%s">%s</a>',
                esc_url(wp_login_url(get_permalink())),
                $args['login_text']
            );
        } else {
            $onclick = sprintf(
                'return addComment.moveForm( "%1$s-%2$s", "%2$s", "%3$s", "%4$s" )',
                $args['add_below'],
                $comment->comment_ID,
                $args['respond_id'],
                $post->ID
            );
            $link = sprintf(
                "<a rel='nofollow' class='comment-reply-link' href='%s' onclick='%s' aria-label='%s'>%s</a>",
                esc_url(add_query_arg('replytocom', $comment->comment_ID, get_permalink($post->ID))) . "#" . $args['respond_id'],
                $onclick,
                esc_attr(sprintf($args['reply_to_text'], $comment->comment_author)),
                $args['reply_text']
            );
        }
        return $link;
    }
}

将如上代码添加至主题functions文件,保存刷新就会恢复评论回复功能。原理是利用WordPress钩子修改“回复”按钮的URL格式,当判断WordPress的版本等于或大于5.1.1时就加载该钩子。

虽说平时也没几个网友使用玩机APP网站的评论回复功能,但一想到网站有bug心里就不爽,今天终于解决了这个心结,非常开心,所以小小的打赏了一下后宫学长,同时也去了代码来源网站做了留言表示感谢。

相关推荐

暂无评论