lundi 24 août 2020

Determine what category product belongs to and show image. - How to clean up this PHP code?

For my Woocommerce shop, I inserted some PHP code in the productpage to show an image. The code below works, but is very maintaining and long. I now have 83 for elseif's.... I know this can be done much better, cleaner and faster.

Probably using a foreach or so. The problem is, the name of the image also contains the productname, which varies. So, basically, 1) I need to determine the categoryname (solved), 2) the productname and 3) call an image called "productname-categoriename.png"

Can somebody help me to reproduce this code, but smarter?

    <?php 
if ( is_product() && has_term( 'category-name', 'product_cat' ) ) {
  echo '<div class="logo"><img src="https://www.website.com/logo/productname-categoryname.png"></div>';
  }
  elseif ( is_product() && has_term( 'category-name-2', 'product_cat' ) ) {
  echo '<div class="logo"><img src="https://www.website.com/logo/productname-categoryname-2.png"></div>'; 
  }
  elseif ( is_product() && has_term( 'category-name-83', 'product_cat' ) ) {
  echo '<div class="logo"><img src="https://www.website.com/logo/productname-category-name-83.png"></div>'; 
  
} else {
  echo "";
}
?>

Aucun commentaire:

Enregistrer un commentaire