Search code examples
wordpresswordpress-themingadvanced-custom-fields

ACF image field in foreach loop for Wordpress


I want to load my ACF field cat_img inside of this loop where it says $cat->image. The existing code block I am working with is:

<?php 
      $cats = get_categories($image = get_field('cat_img'));
      foreach ($cats as $cat) { ?>
        <div class="col-md-6 col-xl-3 mb-4 mx-auto">
          <div class="bg-image ripple rounded-5" data-mdb-ripple-color="light">
            <img class="w-100" src="<?php $cat->image ?>"
              style="height: 288px; object-fit: cover" />
            <a href="'. get_term_link($cat).'">
              <div class="mask" style="background-color: rgba(255,255,255, 0.5)">
                <div class="d-flex justify-content-center align-items-center h-100">
                  <p class="h4 fw-bold text-uppercase text-dark mb-0"><?php echo $cat->name ?></p>
                </div>
              </div>
              <div class="hover-overlay">
                <div class="mask" style="background-color: rgba(255,255,255, 0.1)"></div>
              </div>
            </a>
          </div>
        </div>
      <?php  ;
      }
      ?>

any help on how to get it to show that custom field would be awesome. Thanks for your help!


Solution

  • I was missing this line inside my forEach loop:

    $image = get_field('cat_img', 'category_' . $cat->term_id );
    

    That lets me now run this block of code to get ACF field images as tiles behind the category name (you will see the <? echo $image['url']?> where the image is called):

    <?php
          
          $cats = get_categories();
          foreach ($cats as $cat) {
            $image = get_field('cat_img', 'category_' . $cat->term_id );
          ?>
            <div class="col-md-6 col-xl-3 mb-4 mx-auto">
              <div class="bg-image ripple rounded-5" data-mdb-ripple-color="light">
                <img class="w-100" src="<? echo $image['url']?>"
                  style="height: 288px; object-fit: cover" alt="<? echo get_field('cat_img', $cat->ID) ?> Category Image"/>
                <a href="<? echo get_term_link($cat);?>">
                  <div class="mask" style="background-color: rgba(0,0,0, 0.35)">
                    <div class="d-flex justify-content-center align-items-center h-100">
                      <p class="h4 fw-bold text-uppercase text-light mb-0"><?php echo $cat->name ?></p>
                    </div>
                  </div>
                  <div class="hover-overlay">
                    <div class="mask" style="background-color: rgba(255,255,255, 0.1)"></div>
                  </div>
                </a>
              </div>
            </div>
          <?php  ;
          }
          ?>