• Resolved ccato001

    (@ccato001)


    I am using this code to show images in place of the standard categories:

    <?php
    foreach((get_the_category()) as $category) {
        echo '<img src="https://example.com/images/' . $category->cat_name . '.jpg" alt="' . $category->cat_name . '" />';
    }
    ?>

    This works perfectly, but I would like for the images to also link to the appropriate categories. How do I accomplish this?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    try something like this:

    <?php
    foreach((get_the_category()) as $category) {
      $html = '<a href="' . get_category_link($category->cat_ID) . '">';
      $html .= '<img src="https://example.com/images/' . $category->cat_name . '.jpg" alt="' . $category->cat_name . '" />';
      $html .='</a>';
      echo $html;
    }
    ?>
    Thread Starter ccato001

    (@ccato001)

    This works like a charm. I know I’m stretching it, but is there a way for the Category name to show under each image?

    Moderator keesiemeijer

    (@keesiemeijer)

    You could do something like this (not tested):

    <?php
    foreach((get_the_category()) as $category) {
      $html = '<p class="cat-img">';
      $html .= '<a href="' . get_category_link($category->cat_ID) . '">';
      $html .= '<img src="https://example.com/images/' . $category->cat_name . '.jpg" alt="' . $category->cat_name . '" />';
      $html .='</a><span>' . $category->cat_name . '</span></p>';
      echo $html;
    }
    ?>

    and put this at the bottom of your theme’s style.css:

    .cat-img a {
    	float: left;
    }
    .cat-img span {
    	clear:  left;
    }

    Thread Starter ccato001

    (@ccato001)

    Thanks! Here’s what I ended up doing for it to work.

    To display the images (categories) with the category names underneath:

    <div align="center"><?php
    foreach((get_the_category()) as $category) {
      $html = '<div class="cat-img">';
      $html .= '<a href="' . get_category_link($category->cat_ID) . '">';
      $html .= '<img src="https://www.yoursite.com/images/' . $category->cat_name . '.jpg" alt="' . $category->cat_name . '" />';
      $html .='</a><br>' . $category->cat_name . '</div>';
      echo $html;
    }
    ?></div>

    For the css:

    .cat-img {
    	float:left;
    width:300px;
    text-transform:uppercase;
    padding:15px;
    }

    The width above is equal to the size of the images.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Adding Links to Category Images’ is closed to new replies.