I want to show a "free delivery" badge at every product with a price above 50$. It should be visible on the product page and in the loop.
The problem is, that there could be more than one price. If you think about variations and sales (or even variations with variants on sale). So I need to check the type of the product and have to search for the cheapest price to calculate with.
At the moment I'm using the following code. It works ok sometimes. But on products with no active stock management it produces a timeout on the product page and doesn't work on archives (shows no message). Also it produces some notices about not using the ID directly.
I don't feel safe with that code... Is there a better way to archieve it? I tried a lot of ways but I'm not sure if I think about every possibilities about price, sales, stock or product types?!
<?php add_action( 'wgm_after_tax_display_single', 'wgm_after_tax_display_single_free_delivery', 10, 1 );
function wgm_after_tax_display_single_free_delivery( ) {
if (is_product()):
global $post, $product;
if ( ! $product->is_in_stock() ) return;
$sale_price = get_post_meta( $product->id, '_price', true);
$regular_price = get_post_meta( $product->id, '_regular_price', true);
if (empty($regular_price)){ //then this is a variable product
$available_variations = $product->get_available_variations();
$variation_id=$available_variations[0]['variation_id'];
$variation= new WC_Product_Variation( $variation_id );
$regular_price = $variation ->regular_price;
$sale_price = $variation ->sale_price;
}
if ( $sale_price >= 50 && !empty( $regular_price ) ) :
echo 'free delivery!';
else :
echo 'NO free delivery!';
endif;
endif;
} ?>