Reputation: 319
Is there a way to check and see if a category thumbnail exist in WooCommerce? Something similar to has_post_thumbnail()
? I'm trying to create conditional that will display a category image if available and if not it'll display the WooCommerce placeholder.
CODE UPDATED with answer below for anyone else who needs it:
<?php
$args = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids,
'parent' => 0
);
$product_categories = get_terms( 'product_cat', $args );
foreach( $product_categories as $cat ) {
$category_thumbnail = get_woocommerce_term_meta($cat->term_id, 'thumbnail_id', true);
$image = wp_get_attachment_url($category_thumbnail);
if ($image) {
$image_decider = $image;
} else {
$image_decider = woocommerce_placeholder_img_src();
}
echo '
<div class="col-md-4">
<a href="'. get_site_url().'/product-category/'. $cat->slug .'">
'. $cat->name . '<img src="'.$image_decider.'" width="350" height="350" alt="'. $cat->name . '-category-image"></a>
</div>
';
}
?>
Upvotes: 0
Views: 2575
Reputation: 10132
You can simply use if () {...} else { .. }
conditions to decide whether image exists or not.
Simply use:
if ($image) {
$image_decider = $image;
} else {
$image_decider = 'http://www.example.com/wp-content/themes/your-theme/images/placeholder.png';
}
echo $image_decider; //Image Or Placeholder
Full Code:
<?php
$args = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids,
'parent' => 0
);
$product_categories = get_terms( 'product_cat', $args );
foreach( $product_categories as $cat ) {
$category_thumbnail = get_woocommerce_term_meta($cat->term_id, 'thumbnail_id', true);
$image = wp_get_attachment_url($category_thumbnail);
//Code to paste
if ($image) {
$image_decider = $image;
} else {
//Your placeholder image URI
$image_decider = 'http://www.example.com/wp-content/themes/your-theme/images/placeholder.png';
}
//Code to paste
echo '
<div class="col-md-4">
<a href="'. get_site_url().'/product-category/'. $cat->slug .'">
'. $cat->name . '<img src="'.$image_decider.'" width="350" height="150"
alt="'. $cat->name . '-category-image"></a>
</div>
';
}
?>
Upvotes: 1