Trying to add 'Free Delivery' badge to product thumbnail in Woocommerce based on shipping class

Viewed 245

I wanted to add a 'Free UK Delivery' text badge to products that do not have a shipping class associated with them. This is the very rough code I have so far but this is a new language to me and I'm trying to splice things together and not succeeding very well. Would super appreciate some help:

add_action( 'woocommerce_before_shop_loop_item_title', 'single_product_label', 10 );
function single_product_label() {
    global $product;

    if( $shipping_class = $product->get_shipping_class() ) {
    if ( $shipping_class->is_wp_error) {
              echo '<span class="freedel">Free UK Delivery</span>';
      }
    }
    return '';
  }

and CSS code:

.freedel {
padding: 3px 8px;
text-align: center;
background: #222;
color: white;
font-weight: bold;
position: absolute;
top: 6px;
right: 6px;
font-size: 12px;
}

Thanks in advance, Emma

1 Answers

Your code has errors in it. You can change it to the following

add_action( 'woocommerce_before_shop_loop_item_title', 'single_product_label', 10 );
function single_product_label() {
    global $product;
    if ( empty( $product->get_shipping_class() ) ) {
        echo '<span class="freedel">Free UK Delivery</span>';
    }
  }

I have done a quick check and this shows the label. See the screenshot attached.

enter image description here

Related