Create a dynamic "Free Shipping" Progress bar for Woocommerece widget in Wordpress shortcode

StackOverflow https://stackoverflow.com/questions/22180970

  •  05-06-2023
  •  | 
  •  

Question

I am trying to use the Progress Bar plugin in wordpress to create a widget that shows a progress bar under the shopping cart of how much more they need to spend in order to get free shipping.

I need to first take the value of the cart:

global $woocommerce;
$price = $woocommerce->cart->get_cart_total();

Secondly Strip the dollar sign and round to nearest integer ?

Thirdly Output the value into the shortcode, so it displays properly into the HTML. As it is now, it outputs this for the width instead of a number.<span class="red" style="width: .$cartnumber%;">

I need this to output a plain number so it will work with the width. Below is the code so far.

<?php
global $woocommerce;
$total = $woocommerce->cart->get_cart_total();
$cartnumber = str_replace("&#36;", "", $total);
echo do_shortcode('[wppb progress='.$cartnumber.' option=red text="Free Shipping"]');
?>

I have enabled PHP execution within widgets for

No correct solution

OTHER TIPS

I have encountered this before, and below is what I have used last. http://www.php.net/manual/en/class.numberformatter.php

Before I am using preg_match using [0-9\,\s.]+ pattern. Then I have replaced all special characters and letters to blank to get the integer. (not a good solution)

Example code taken from http://www.pagecolumn.com/tool/pregtest.htm

<?php 
    $ptn = "/[0-9\,\s\.]+/";
    $str = "$9,988,776.65 in the United States";
    preg_match($ptn, $str, $matches);
    print_r($matches);
?>

Output

Array
(
 [0] => 9,988,776.65
)

After I realised that it was not a good solution, I revised it to simpler solution using the code below. from: Remove non-numeric characters (except periods and commas) from a string

$number = "$9,988,776.65";
echo preg_replace("/[^0-9]/", "", $number);

Output

998877665

if you did not remove the thousands and decimal symbol it will get the number format of the currency.

Regarding the progress bar, you need to convert the totals to 100%. I assume that your formula is similar below:

(price/free_shipping_minimum)*100

if result goes over 100 then set it to 100%. if you don't want decimals in your percentage cast it to int or use php's round/ceil/floor function.

http://www.php.net/manual/en/function.round.php

I hope this helps a lot.

Why you don't use

WC()->cart->subtotaĺ

Return a float, so no need to remove $ sign

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top