Skip to content
Advertisement

Display only 10 List Items using PHP?

I have built a subcategory widget, which pulls all subcategories from a parent cat ID and displays them as list items. I only want to display 10 list items and beyond that, display a “view all” link that links back to the parent cat ID. How can I accomplish this using my front end code below?

    foreach ($subCats as $subcat) {
        $_category = $objectManager->create('MagentoCatalogModelCategory')->load($subcat->getId());
        $subcaturl = $subcat->getUrl();
        } ?>
                        <li class="cat-li" style="list-style-type: none;">
                            <div class="product-item-info">

                                <div class="product-item-details">
                                    <ul class="productsub-categories" style="text-align: left;">
                                       <a href="<?php echo $subcaturl; ?>">
                                            <strong ><?php echo $subcat->getName(); ?></strong>
                                        </a>
                                    </ul>
                                </div>
                            </div>
                        </li>

Advertisement

Answer

First, your HTML is not in the loop. Second, just increment a counter and check for 10 and break:

$i = 0;
foreach ($subCats as $subcat) {
    if($i == 10) { break; } $i++;
    $_category = $objectManager->create('MagentoCatalogModelCategory')->load($subcat->getId());
    $subcaturl = $subcat->getUrl();
    ?>
                    <li class="cat-li" style="list-style-type: none;">
                        <div class="product-item-info">

                            <div class="product-item-details">
                                <ul class="productsub-categories" style="text-align: left;">
                                   <a href="<?php echo $subcaturl; ?>">
                                        <strong ><?php echo $subcat->getName(); ?></strong>
                                    </a>
                                </ul>
                            </div>
                        </div>
                    </li>
    <?php }

    echo "Your view all link";
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement