0
votes

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 "";
}
?>
1
How do you get the product name? - Andy
I can use "$product->get_name();" for that. - Denny

1 Answers

0
votes

You're going to get a lot of different answers, but here's one approach:

<?php    

if (is_product()) {
    $productName = $product->get_name();
    // however you get the category name
    $categoryName = '';     
    $iconName = "{$productName}-{$categoryName}.png";
    $output = '<div class="logo"><img src="https://www.website.com/logo/' . $iconName . '"></div>'
}

echo $output ?? '';

You're going to need to adhere to keeping the naming convention that you've applied to the png files.