PHP Foreach循环:实现仅包裹超10条的剩余项求助
Got it, let's fix this for you! The key here is to track our position in the loop, then open a single "show more" container once we hit the 10th item, and dump all remaining terms into it. Here's the modified, complete code that does exactly that:
<ul> <li><a href="#">Visas preces</a></li> <?php $childid = get_product_top_level_category(get_the_ID()); $args = array( 'taxonomy' => 'product_cat', 'parent' => $childid ); $terms = get_terms($args); $i = 1; $show_more_container_open = false; // Track if we've started the submenu foreach($terms as $term) { if ($i <= 10) { // Output the first 10 items as regular list items echo '<li><a href="'.get_term_link($term).'">'.$term->name.'</a></li>'; } else { if (!$show_more_container_open) { // Open the "show more" container ONCE before the first remaining item echo '<li class="show-more"> <a href="#">Show More</a> <ul class="submenu">'; $show_more_container_open = true; } // Add all remaining items inside the submenu echo '<li><a href="'.get_term_link($term).'">'.$term->name.'</a></li>'; } $i++; } // Close the submenu and container if we opened them if ($show_more_container_open) { echo '</ul></li>'; } ?> </ul>
Quick Breakdown of the Logic:
- Loop Position Tracking: The
$icounter lets us know when we've passed the 10th item. - Single Container: The
$show_more_container_openflag ensures we only create the "show more" submenu once—no duplicate containers cluttering up your HTML. - Clean HTML Closure: After the loop, we check if we opened the submenu and close it properly to avoid broken markup.
You can add CSS to the .show-more and .submenu classes to make the dropdown functional (like hiding the submenu by default and showing it on click).
内容的提问来源于stack exchange,提问作者Foxsk8
相关产品推荐
相关产品推荐

