如何将Bootstrap站点PHP评论默认显示数从13改为2?
Hey there! Let's fix this comment display issue for you. Right now, your code shows all comments by default and only displays the "load more" button when votes exceed 4—we need to adjust both the default display count and the button visibility condition to match your goal of showing 2 comments initially.
Here's what you need to do step by step:
1. Limit Default Visible Comments to 2
Instead of looping through all $post_data['comments'], we'll only iterate over the first 2 entries. You can use array_slice() for clean, concise code:
2. Adjust the "Load More" Button Condition
Replace the vote-based check with a check on the total number of comments—we only want the button to appear if there are more than 2 comments total.
3. Update the Load Function (If Needed)
Your load_tlp_comments function needs to know to load comments starting from index 2 (since we've already shown the first 2). Make sure the function accepts an offset parameter, or update its backend logic to skip the first 2 comments when triggered.
Modified Code Example
<li class="pp_post_comms hidden"></li> <?php if ($post_data['comments']) { // Only render the first 2 comments by default foreach (array_slice($post_data['comments'], 0, 2) as $key => $comment) { include 'comments.html'; } } ?> <?php // Show the "load more" button only when total comments exceed 2 $total_comments = count($post_data['comments']); if ($total_comments > 2) { ?> <li class="load-comments"> <!-- Pass offset=2 to the load function (adjust if your function expects this parameter) --> <button onclick="load_tlp_comments(<?php echo $post_data['post_id']; ?>, this, 2);">{{LANG show_more}} {{LANG comments}}</button> </li> <?php } ?> </ul>
Quick Alternatives & Notes:
- If you prefer a loop condition over
array_slice(), you can rewrite the loop like this:foreach ($post_data['comments'] as $key => $comment) { if ($key < 2) { // Only render first 2 comments include 'comments.html'; } } - For the backend part of
load_tlp_comments, ensure your SQL query uses an offset (e.g.,LIMIT 2, 10to fetch 10 comments starting from the 3rd one) to avoid reloading the first 2 comments again.
That should do it! Now your posts will show 2 comments by default, and the "view more" button will appear only when there are additional comments to load.
内容的提问来源于stack exchange,提问作者Dohn Joe

