PHP to loop a list presented in a table – I cannot understand how it works

This is my first time modifying somebody else’s WordPress theme and I cannot figure out how this code works exactly.

The following code generates a list in a table that has 3 columns and infinite rows. How does this code define the number of columns? How would I change 3 columns to 5, etc?

<table class="brands">
                <tbody>
                <?php if($terms): ?>
                <?php foreach($terms as $term): ?>
                <tr>
                    <?php
                        foreach($term as $tr):
                        $term_name = $tr->name;
                        $term_id = $tr->term_id;
                        $term_thumb = get_field("thumbnail","{$listing_cat}_{$term_id}");
                        $term_link = get_term_link($tr->slug,$listing_cat);
                    ?>
                        <td>
                            <a href="<?php echo $term_link; ?>">
                                <?php if($term_thumb): ?>
                                    <img src="<?php echo $term_thumb["url"]; ?>" alt="<?php echo $term_name; ?>">
                                <?php endif; ?>
                                <p><?php echo $term_name; ?></p>
                            </a>
                        </td>
                    <?php endforeach; ?>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>

Related posts

Leave a Reply

2 comments

  1. Try,

    <?php
    
    print_r($term);
    
    foreach($term as $tr):
    

    you might notice that count($term) = 3, that’s why it is printing 3 columns. Well, for hainvg more columns, try push more elements in your $term.

    As for “infinite rows”, that rather depends on the length of your $terms array.

  2. Its displaying 3 columns because of the no of default $terms in the theme’s database. It is running a loop for each $item, so basically for you to run 5 columns you will have to either push items to the database table or you can skip checking for $item and run a loop as

    <table class="brands">
        <tbody>
           <?php for(i=0; i<5, i++){ ?>
                  <tr>
                      <?php
                         //what you want to display
                      ?>
                        <td>
                            //your table data
                        </td>
    
                  </tr>
           <?php }?>
       </tbody>