Search code examples
phpwordpressforeachwarningsinvalid-argument

PHP Warning: Invalid argument supplied for foreach() on line 61 of my code


Im working on a custom code right now and I get this warning about an invalid argument for foreach()

Here is my code below and the line 61 is the tags as tag:

<h3 class="mt-5 mb-3 h2 font-weight-light text-center">Categories</h3>

                        <div class="grid-columns">
                            <?php foreach( $page_context->tags->items as $item ) :
                                foreach( $item as $tags ) :
                                    if(isset($tags)):
                                        echo('<div style=\'display: none;\'>');
                                        echo ($tags);
                                        echo('</div>');
                                    foreach( $tags as $tag ) : ?>

                                      
                                        <button class="card library-tag" data-id="<?= $tag->id; ?>">
                                            <a class="disabled" aria-label="<?= $tag->name ?>" href="/catalog/#category-<?= $tag->id; ?>">
                                            <div class="panel-box shadow-box">
                                                <img class="card-img-top" src="<?= $tag->thumbnailPath ?>" alt="<?= $tag->name ?>a">
                                                <div class="card-body border-top">
                                                    <h6 class="card-title"><?= $tag->name ?></h6>
                                                </div>
                                            </div>
                                            </a>
                                        </button>
                              <?php endforeach;
                                    endif;
                                endforeach;
                            endforeach; ?>
                        </div>
                </div>
            </section>

Solution

  • Add these three lines of code to troubleshoot.
    You see why the foreach does not work

    <?php foreach( $page_context->tags->items as $item ) :
        foreach( $item as $tags ) :
            if(isset($tags)):
                echo('<div style=\'display: none;\'>');
                echo ($tags);
                echo('</div>');
                
                echo '<pre>';
                var_export($tags);
                exit;
                
            foreach( $tags as $tag ) : ?>