检查是否存在WooCommerce类别图像

时间:2014-02-12 18:39:30

标签: wordpress woocommerce

有没有办法检查并查看WooCommerce中是否存在类别缩略图?与has_post_thumbnail()类似的东西?我正在尝试创建条件,如果可用则显示类别图像,否则它将显示WooCommerce占位符。

代码更新了以下答案,以满足其他任何需要它的人:

<?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>
                ';
            }
        ?>

1 个答案:

答案 0 :(得分:1)

您只需使用if () {...} else { .. }条件来判断图像是否存在。

只需使用:

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

完整代码:

<?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>
                ';
            }
 ?>