I have a function that is getting a string of "lead time" in WooCommerce. An example would be:Available! Estimated Lead Time: 2-3 Weeks
. I want to get the 2-3 Weeks
. So far, I've been able to do it with the following function:
function display_lead_time_notice_card() {
global $product;
//Get Stock Status
$in_stock = $product->get_availability()['class'];
//If In Stock, parse the lead time
if ($in_stock == 'in-stock') {
//Lead Time Statement:
$availability = $product->get_availability()['availability'];
// Extract "2-3 Weeks"
preg_match('/[0-9]-[0-9] Weeks/', $availability, $matches, PREG_OFFSET_CAPTURE, 0);
// Get Lead Time
$lead_time = $matches[0][0];
echo '
<div >
<h4>A note on lead times:</h4>
<p >A Lead Time of ' . $lead_time . ' is just an estimate. Lead Times are subject to change depending on the current shop capacity and size of the order. We will always try to complete your order quicker than the stated lead time.</p>
</div>
';
}
}
add_action('woocommerce_single_variation', 'display_lead_time_notice_card', 10);
This is working, but I'm wondering if there's a cleaner, simpler way to extract the substring from the $availability
variable.
CodePudding user response:
It's hard to believe that it will always be weeks, might it be days or months?
That being said, if the string is consistent, just explode
on the colon and space:
$lead_time = explode(': ', $availability)[1];
For fun:
$lead_time = ltrim($availability, 'A..z!: ');