Is it possible to display a different image for each Category type in Wordpress?

Asked

Viewed 315 times

1

I have a Wordpress page with some posts, and they present some categories, but we will define them as: cat1, cat2 and cat3.

Within the loop of Wordpress are displayed three posts, each with its own category and they have a different image for each one, an example of this is:

  • In cat1, the posts that have this category, will have an image in the corner written: 50% Off.
  • In cat2, the posts that have this category, will have an image in the corner, written: 70% Off.
  • In cat3, follows the same criterion...

I already have a code, and this is where my big problem comes in, it’s too repetitive and it bothers me. I have a set of three pictures with different names and sizes.

They are being called within several if, following example:

$category = get_cat_name();
if ( $category == "cat1" ) {
   echo "<img src='...'> "
}
if ( $category == "cat2" ) {
   echo "<img src='...'> "
}

There is possibility to create this same content without a huge repeat?


UPDATE: I tried to create a foreach, but I ended up crashing on how to pull the images according to the selected category, the code stayed that way:

$cat_name = get_cat_name();
$test = ["cat1", "cat2", "cat3"];
$images = ["img1.jpg", "img2.jpg", "img3.jpg"];

foreach ( $test as $t ) {
   if ( $cat_name == $t ) {
      $image = "<img src='./* Aqui que estou confuso */.'>";
   }
} 
  • You can use parameters within your parole.

  • @durtto right now I tried an array of objects and then a foreach, but ended up impaling on how to call the images in an orderly way (according to foreach category).

  • Wouldn’t it be the case to simply rename the images to Slug (short name) of the categories? There is no foreach... This would be the case for another question, but can you put an extra field in the categories, on site.com/wp-admin/Edit-tags.php? taxonomy=Category

1 answer

1

My suggestion would be to use Switch instead of for. each...

$categories = get_the_terms( $post->ID ); //pega categoria do post corrente
$cat_name = $category->slug; // pega o slug ao inves do nome da categoria pois esse pode ter espaços e acentos e vai dar problema no código
$image_tag = ""; // vai montar a tag de imagem com o valor correto

switch ( $cat_name ){ 
    case "cat1": $image = "img1.jpg"; break;
    case "cat2": $image = "img2.jpg"; break;
    case "cat3": $image = "img3.jpg"; break;
    default: $image = "placeholder.jpg"; break;
}

$image_tag = "<img src=./assets/images/". $image .">";
echo $image_tag;

Reference: https://developer.wordpress.org/reference/functions/get_the_category/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.