How can I wrap the content using a permalink in a foreach loop

Viewed 34

How can I wrap the content in the overlay div with a permalink that corresponds to the category. I want the image to be clickable and also pull the category name with the matching image. I want this to be dynamic in the event new categories are added.

<?php
/**
 * 
 * Catergory Display
 * 
 */

$categories = get_categories( array(
    'orderby' => 'name',
    'order'   => 'ASC',
    'hide_empty'      => false,
) );

 ?>

<div class="container">
    <div class="row">

 <?php

foreach( $categories as $category ) {
    $image = get_field('category_image', 'category_' . $category->term_id);

    $size = 'featured-thumbnail'; // (thumbnail, medium, large, full or custom size)
    $cat_link = get_category_link($category->cat_ID);
      

     ?>
    
    <div class="category-holder col-lg-4 col-md-6 col-sm-12 ">
            <div class="category-display-img"> 
             
                <?php echo wp_get_attachment_image( $image, $size ); ?>   
                <a href="<?php echo esc_url( get_permalink($cat_link) )?>">
            <div class="overlay"><?php echo '<a class="" href="'.$cat_link.'">'.$category->name.'</a>'; // category link ?></div>
                </a>
            </div>

            
    </div>
           
           <?php
    // echo '<pre>';
    // print_r($cat_link);
    // wp_die();
} ?>

   </div>
</div>
1 Answers

You can wrap the anchor tag around the div with the overlay class.

Delete this part

<a href="<?php echo esc_url( get_permalink($cat_link) )?>">
            <div class="overlay"><?php echo '<a class="" href="'.$cat_link.'">'.$category->name.'</a>'; // category link ?></div>
                </a>

And use this in its place

<a href="<?php echo $cat_link ?>">
    <div class="overlay">
        <?php echo $category->name ?>
    </div>
</a>
Related