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;
} ?>
As you are using a custom hook, is difficult to test it for real (the same way as you)… Now this revisited code should work in a much better way than yours (solving error notices):
add_action( 'wgm_after_tax_display_single', 'wgm_after_tax_display_single_free_delivery', 10, 1 );
function wgm_after_tax_display_single_free_delivery() {
// On single product pages and archives pages
if ( is_product() || is_shop() || is_product_category() || is_product_tag() ):
global $post, $product;
if ( ! $product->is_in_stock() ) return;
// variable products (get min prices)
if ( $product->is_type('variable') ) {
$sale_price = $product->get_variation_sale_price('min');
$regular_price = $product->get_variation_regular_price('min');
}
// Other products types
else {
$sale_price = $product->get_sale_price();
$regular_price = $product->get_regular_price();
}
$price = $sale_price > 0 ? $sale_price : $regular_price;
if ( $price >= 50 ) {
echo __('free delivery!');
} else {
echo __('NO free delivery!');
}
endif;
}
Code goes in function.php file of your active child theme (or active theme). It should work better.