php – Show div only if product has attribute

Question

I have this code that adds a <span> below the product price, which is the price per square meter.

My issue is, I want it to show ONLY if the product attribute is available, as I do not have this information for all products.

I’m sure it is just a small tweak but I have tried a few things to no avail. Here’s the code:

add_action( 'woocommerce_after_shop_loop_item_title', 'display_m2price_attribute', 5 );
function display_m2price_attribute() {
    global $product;

    if ( $product ) {
        $taxonomy = 'pa_m²-price';
        echo '<span class="attribute-m2price"> (£' . $product->get_attribute($taxonomy) . ' per m²)</span>';
    }
}

0
Ste Bell 2 months 2022-10-16T11:07:20-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse