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

Time:02-10

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 >
    <div >

 <?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 >
            <div > 
             
                <?php echo wp_get_attachment_image( $image, $size ); ?>   
                <a href="<?php echo esc_url( get_permalink($cat_link) )?>">
            <div ><?php echo '<a  href="'.$cat_link.'">'.$category->name.'</a>'; // category link ?></div>
                </a>
            </div>

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

   </div>
</div>

CodePudding user response:

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 ><?php echo '<a  href="'.$cat_link.'">'.$category->name.'</a>'; // category link ?></div>
                </a>

And use this in its place

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