You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP Foreach循环:实现仅包裹超10条的剩余项求助

Solution: Wrap All Remaining Items in a "Show More" Submenu

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 $i counter lets us know when we've passed the 10th item.
  • Single Container: The $show_more_container_open flag 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:24:53