WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Adding Links to Category Images (5 posts)

  1. ccato001
    Member
    Posted 4 years ago #

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

    <?php
    foreach((get_the_category()) as $category) {
        echo '<img src="http://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?

  2. keesiemeijer
    moderator
    Posted 4 years ago #

    try something like this:

    <?php
    foreach((get_the_category()) as $category) {
      $html = '<a href="' . get_category_link($category->cat_ID) . '">';
      $html .= '<img src="http://example.com/images/' . $category->cat_name . '.jpg" alt="' . $category->cat_name . '" />';
      $html .='</a>';
      echo $html;
    }
    ?>
  3. ccato001
    Member
    Posted 4 years ago #

    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?

  4. keesiemeijer
    moderator
    Posted 4 years ago #

    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="http://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;
    }
  5. ccato001
    Member
    Posted 4 years ago #

    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="http://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.

Topic Closed

This topic has been closed to new replies.

About this Topic