I am looking to create a function that would allow me to display an image with the "slug name" of the product, but only if this image is present in the folder, and which displays a placeholder image if this image does not exist !
Here is my current code:
function custom_hero_image( $post_id ) {
$product = get_post( $post_id );
$slug = $product->post_name;
if ( is_product( $post_id ) ) {
if ( has_post_thumbnail() ) {
$html = '<img class="jarallax-img" src="'. get_template_directory_uri() .'/inc/assets/img/shop/hero/'.$slug.'_hero.jpg">';
}
} else {
$html = '<img class="jarallax-img" src="'. get_template_directory_uri() .'/inc/assets/img/hero/shop-hero.jpg">';
}
return $html;
}
And this is the code for the single-product.php file
<?php
// get the post ID outside the Loop
$post_id = get_queried_object_id();
// print the <img>
echo custom_hero_image( $post_id );
?>
In this code, the image is well displayed when it exists but when there is no image to display, the placeholder image is not displayed!
Could you help me and tell me where is my mistake?
Let me know if you have any questions.
2
Answers
you can just simply use
onerror
attribute on the image tag, this will fired if the image cannot be accessed, or usefile_exists
function to determine if the image is exists,Simple ways:
Using
file_exists
: