WordPress如何在其他地方调用本篇文章作者的所有评论,多的折叠起来,点击展示,自动
在WordPress中实现一个功能,即在其他地方调用当前文章作者的评论,并且将多余的评论折叠起来,通过点击展示,可以使用以下几种方法:
方法1:使用自定义函数和模板标签
创建自定义函数:首先,创建一个PHP函数来获取并显示指定作者的评论。
function display_author_comments($post_id) {
$comments = get_comments(array(
'post_id' => $post_id,
'status' => 'approve',
'number' => 10 // 显示前10条评论
));
if ($comments) {
echo '<div class="author-comments">';
echo '<h3>Comments by Author</h3>';
echo '<div class="comments-list">';
foreach ($comments as $comment) {
echo '<div class="comment">';
echo '<div class="comment-author">' . get_avatar($comment, 40) . ' ' . get_comment_author($comment->comment_ID) . '</div>';
echo '<div class="comment-text">' . get_comment_text($comment->comment_ID) . '</div>';
echo '</div>';
}
echo '</div>';
echo '<button class="show-more">Show More Comments</button>';
echo '</div>';
} else {
echo '<p>No comments found.</p>';
}
}
添加折叠功能:使用JavaScript来折叠多余的评论。
<script>
document.addEventListener('DOMContentLoaded', function() {
const commentsList = document.querySelector('.comments-list');
const showMoreBtn = document.querySelector('.show-more');
let allComments = Array.from(commentsList.querySelectorAll('.comment'));
let visibleComments = allComments.slice(0, 10); // 默认显示前10条评论
let hiddenComments = allComments.slice(10); // 剩余的评论
hiddenComments.forEach(comment => comment.style.display = 'none'); // 隐藏剩余评论
showMoreBtn.addEventListener('click', function() {
hiddenComments.forEach(comment => comment.style.display = 'block'); // 显示隐藏的评论
this.style.display = 'none'; // 隐藏“显示更多”按钮
});
});
</script>
在模板中调用:在你的主题文件(如 single.php 或其他需要显示评论的模板)中调用这个函数。
<?php
$post_id = get_the_ID(); // 获取当前文章的ID
display_author_comments($post_id);
?>
方法2:使用插件或第三方库
如果你不想手动编写JavaScript和PHP代码,可以考虑使用一些现有的插件或库,例如“Advanced Comments”或“Custom Comment Walker”等插件,这些插件提供了更多的自定义选项和折叠功能。安装并激活这些插件后,你可以在插件的设置中找到折叠评论的选项,并进行配置。
方法3:使用WordPress的钩子(Hooks)和动作(Actions)
如果你熟悉WordPress的钩子系统,你可以通过添加动作(actions)来动态添加折叠评论的逻辑。例如,使用wp_footer钩子来添加JavaScript代码。
function add_custom_scripts() {
wp_enqueue_script('custom-comments-script', get_template_directory_uri() . '/js/custom-comments.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'add_custom_scripts');
然后,在你的js/custom-comments.js文件中添加折叠逻辑。
以上方法可以帮助你在WordPress中实现调用并折叠显示当前文章作者的评论。选择最适合你需求的方法来实现。
提示:AI自动生成,仅供参考
参考 |