Can I display a different image for each Category type in Wordpress?

0

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

Within loop of Wordpress, three posts are displayed, each with its 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% with%, the% with% that has this category will have a corner image, typed: 70% Off.
  • In cat2 , follow the same criteria ...

I already have a code, and that's where my big problem comes from, it's too repetitive and it bothers me. I have a set of three images with different names and sizes.

They are being called within several posts , following example:

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

Is it possible to create this same content without a huge repetition?

UPDATE: I tried to create a cat3 , but I ended up locking in how to pull the images according to the selected category, the code looks like this:

$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 */.'>";
   }
} 
    
asked by anonymous 11.01.2016 / 16:38

1 answer

0

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: link

    
25.10.2018 / 13:59