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0-beta.1 3.2.2 6.3.0-rc.1 3.2.3 6.3.0-rc.2 3.2.4 6.3.1 3.2.5 6.3.2 3.2.6 6.4.0 3.3.0 6.4.0-beta.1 3.3.1 6.4.0-rc.1 3.3.2 6.4.1 3.3.2-rc.1 6.4.2 3.3.3 6.5.0 3.3.4 6.5.0-beta.1 3.3.5 6.5.0-rc.1 3.3.6 6.5.0-rc.2 3.4.0 6.5.1 3.4.0-beta.1 6.5.2 3.4.0-rc.2 6.6.0 3.4.1 6.6.0-beta.1 3.4.2 6.6.0-rc.1 3.4.3 6.6.0-rc.2 3.4.4 6.6.1 3.4.5 6.6.2 3.4.6 6.7.0 3.4.7 6.7.0-beta.1 3.4.8 6.7.0-beta.2 3.5.0 6.7.0-rc.1 3.5.0-beta.1 6.7.1 3.5.0-rc.1 6.8.0 3.5.0-rc.2 6.8.0-beta.1 3.5.1 6.8.0-beta.2 3.5.10 6.8.0-rc.1 3.5.2 6.8.1 3.5.3 6.8.2 3.5.4 6.8.3 3.5.5 6.9.0 3.5.6 6.9.0-beta.1 3.5.7 6.9.0-beta.2 3.5.8 6.9.0-rc.1 3.5.9 6.9.1 3.6.0 6.9.2 3.6.0-beta.1 6.9.3 3.6.0-rc.1 6.9.4 3.6.0-rc.2 6.9.5 3.6.0-rc.3 7.0.0 3.6.1 7.0.0-beta.1 3.6.2 7.0.0-beta.2 3.6.3 7.0.0-beta.3 3.6.4 7.0.0-rc.1 3.6.5 7.0.0-rc.2 3.6.6 7.0.1 3.6.7 7.0.2 3.7.0 7.1.0 3.7.0-beta.1 7.1.0-beta.1 3.7.0-rc.1 7.1.0-beta.2 3.7.0-rc.2 7.1.0-rc.1 3.7.1 7.1.0-rc.2 3.7.2 7.1.1
woocommerce / includes / wc-formatting-functions.php
woocommerce / includes Last commit date
abstracts 3 years ago admin 3 years ago blocks 5 years ago cli 3 years ago customizer 4 years ago data-stores 3 years ago emails 3 years ago export 3 years ago gateways 3 years ago import 4 years ago integrations 4 years ago interfaces 4 years ago legacy 3 years ago libraries 3 years ago log-handlers 4 years ago payment-tokens 5 years ago queue 4 years ago react-admin 3 years ago rest-api 3 years ago shipping 4 years ago shortcodes 4 years ago theme-support 3 years ago tracks 3 years ago traits 5 years ago walkers 5 years ago wccom-site 5 years ago widgets 4 years ago class-wc-ajax.php 4 years ago class-wc-api.php 4 years ago class-wc-auth.php 4 years ago class-wc-autoloader.php 5 years ago class-wc-background-emailer.php 5 years ago class-wc-background-updater.php 5 years ago class-wc-breadcrumb.php 5 years ago class-wc-cache-helper.php 4 years ago class-wc-cart-fees.php 5 years ago class-wc-cart-session.php 4 years ago class-wc-cart-totals.php 4 years ago class-wc-cart.php 4 years ago class-wc-checkout.php 4 years ago class-wc-cli.php 3 years ago class-wc-comments.php 3 years ago class-wc-countries.php 4 years ago class-wc-coupon.php 4 years ago class-wc-customer-download-log.php 5 years ago class-wc-customer-download.php 4 years ago class-wc-customer.php 4 years ago class-wc-data-exception.php 8 years ago class-wc-data-store.php 6 years ago class-wc-datetime.php 4 years ago class-wc-deprecated-action-hooks.php 8 years ago class-wc-deprecated-filter-hooks.php 4 years ago class-wc-discounts.php 3 years ago class-wc-download-handler.php 4 years ago class-wc-emails.php 5 years ago class-wc-embed.php 5 years ago class-wc-form-handler.php 4 years ago class-wc-frontend-scripts.php 4 years ago class-wc-geo-ip.php 4 years ago class-wc-geolite-integration.php 6 years ago class-wc-geolocation.php 3 years ago class-wc-https.php 4 years ago class-wc-install.php 3 years ago class-wc-integrations.php 5 years ago class-wc-log-levels.php 5 years ago class-wc-logger.php 4 years ago class-wc-meta-data.php 4 years ago class-wc-order-factory.php 5 years ago class-wc-order-item-coupon.php 4 years ago class-wc-order-item-fee.php 4 years ago class-wc-order-item-meta.php 4 years ago class-wc-order-item-product.php 4 years ago class-wc-order-item-shipping.php 4 years ago class-wc-order-item-tax.php 4 years ago class-wc-order-item.php 4 years ago class-wc-order-query.php 4 years ago class-wc-order-refund.php 3 years ago class-wc-order.php 3 years ago class-wc-payment-gateways.php 4 years ago class-wc-payment-tokens.php 5 years ago class-wc-post-data.php 3 years ago class-wc-post-types.php 3 years ago class-wc-privacy-background-process.php 5 years ago class-wc-privacy-erasers.php 4 years ago class-wc-privacy-exporters.php 4 years ago class-wc-privacy.php 4 years ago class-wc-product-attribute.php 4 years ago class-wc-product-download.php 4 years ago class-wc-product-external.php 5 years ago class-wc-product-factory.php 5 years ago class-wc-product-grouped.php 8 years ago class-wc-product-query.php 5 years ago class-wc-product-simple.php 5 years ago class-wc-product-variable.php 4 years ago class-wc-product-variation.php 4 years ago class-wc-query.php 4 years ago class-wc-rate-limiter.php 4 years ago class-wc-regenerate-images-request.php 3 years ago class-wc-regenerate-images.php 3 years ago class-wc-register-wp-admin-settings.php 4 years ago class-wc-rest-authentication.php 5 years ago class-wc-rest-exception.php 5 years ago class-wc-session-handler.php 4 years ago class-wc-shipping-rate.php 4 years ago class-wc-shipping-zone.php 5 years ago class-wc-shipping-zones.php 5 years ago class-wc-shipping.php 4 years ago class-wc-shortcodes.php 5 years ago class-wc-structured-data.php 5 years ago class-wc-tax.php 4 years ago class-wc-template-loader.php 4 years ago class-wc-tracker.php 4 years ago class-wc-validation.php 5 years ago class-wc-webhook.php 5 years ago class-woocommerce.php 3 months ago wc-account-functions.php 5 years ago wc-attribute-functions.php 3 years ago wc-cart-functions.php 4 years ago wc-conditional-functions.php 4 years ago wc-core-functions.php 3 years ago wc-coupon-functions.php 5 years ago wc-deprecated-functions.php 4 years ago wc-formatting-functions.php 3 years ago wc-notice-functions.php 5 years ago wc-order-functions.php 3 years ago wc-order-item-functions.php 5 years ago wc-page-functions.php 5 years ago wc-product-functions.php 3 years ago wc-rest-functions.php 3 years ago wc-stock-functions.php 4 years ago wc-template-functions.php 3 years ago wc-template-hooks.php 5 years ago wc-term-functions.php 3 years ago wc-update-functions.php 3 years ago wc-user-functions.php 3 years ago wc-webhook-functions.php 4 years ago wc-widget-functions.php 5 years ago
wc-formatting-functions.php
1524 lines
1 <?php
2 /**
3 * WooCommerce Formatting
4 *
5 * Functions for formatting data.
6 *
7 * @package WooCommerce\Functions
8 * @version 2.1.0
9 */
10
11 use Automattic\WooCommerce\Utilities\NumberUtil;
12
13 defined( 'ABSPATH' ) || exit;
14
15 /**
16 * Converts a string (e.g. 'yes' or 'no') to a bool.
17 *
18 * @since 3.0.0
19 * @param string|bool $string String to convert. If a bool is passed it will be returned as-is.
20 * @return bool
21 */
22 function wc_string_to_bool( $string ) {
23 return is_bool( $string ) ? $string : ( 'yes' === strtolower( $string ) || 1 === $string || 'true' === strtolower( $string ) || '1' === $string );
24 }
25
26 /**
27 * Converts a bool to a 'yes' or 'no'.
28 *
29 * @since 3.0.0
30 * @param bool|string $bool Bool to convert. If a string is passed it will first be converted to a bool.
31 * @return string
32 */
33 function wc_bool_to_string( $bool ) {
34 if ( ! is_bool( $bool ) ) {
35 $bool = wc_string_to_bool( $bool );
36 }
37 return true === $bool ? 'yes' : 'no';
38 }
39
40 /**
41 * Explode a string into an array by $delimiter and remove empty values.
42 *
43 * @since 3.0.0
44 * @param string $string String to convert.
45 * @param string $delimiter Delimiter, defaults to ','.
46 * @return array
47 */
48 function wc_string_to_array( $string, $delimiter = ',' ) {
49 return is_array( $string ) ? $string : array_filter( explode( $delimiter, $string ) );
50 }
51
52 /**
53 * Sanitize taxonomy names. Slug format (no spaces, lowercase).
54 * Urldecode is used to reverse munging of UTF8 characters.
55 *
56 * @param string $taxonomy Taxonomy name.
57 * @return string
58 */
59 function wc_sanitize_taxonomy_name( $taxonomy ) {
60 return apply_filters( 'sanitize_taxonomy_name', urldecode( sanitize_title( urldecode( $taxonomy ?? '' ) ) ), $taxonomy );
61 }
62
63 /**
64 * Sanitize permalink values before insertion into DB.
65 *
66 * Cannot use wc_clean because it sometimes strips % chars and breaks the user's setting.
67 *
68 * @since 2.6.0
69 * @param string $value Permalink.
70 * @return string
71 */
72 function wc_sanitize_permalink( $value ) {
73 global $wpdb;
74
75 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
76
77 if ( is_wp_error( $value ) ) {
78 $value = '';
79 }
80
81 $value = esc_url_raw( trim( $value ) );
82 $value = str_replace( 'http://', '', $value );
83 return untrailingslashit( $value );
84 }
85
86 /**
87 * Gets the filename part of a download URL.
88 *
89 * @param string $file_url File URL.
90 * @return string
91 */
92 function wc_get_filename_from_url( $file_url ) {
93 $parts = wp_parse_url( $file_url );
94 if ( isset( $parts['path'] ) ) {
95 return basename( $parts['path'] );
96 }
97 }
98
99 /**
100 * Normalise dimensions, unify to cm then convert to wanted unit value.
101 *
102 * Usage:
103 * wc_get_dimension( 55, 'in' );
104 * wc_get_dimension( 55, 'in', 'm' );
105 *
106 * @param int|float $dimension Dimension.
107 * @param string $to_unit Unit to convert to.
108 * Options: 'in', 'm', 'cm', 'm'.
109 * @param string $from_unit Unit to convert from.
110 * Defaults to ''.
111 * Options: 'in', 'm', 'cm', 'm'.
112 * @return float
113 */
114 function wc_get_dimension( $dimension, $to_unit, $from_unit = '' ) {
115 $to_unit = strtolower( $to_unit );
116
117 if ( empty( $from_unit ) ) {
118 $from_unit = strtolower( get_option( 'woocommerce_dimension_unit' ) );
119 }
120
121 // Unify all units to cm first.
122 if ( $from_unit !== $to_unit ) {
123 switch ( $from_unit ) {
124 case 'in':
125 $dimension *= 2.54;
126 break;
127 case 'm':
128 $dimension *= 100;
129 break;
130 case 'mm':
131 $dimension *= 0.1;
132 break;
133 case 'yd':
134 $dimension *= 91.44;
135 break;
136 }
137
138 // Output desired unit.
139 switch ( $to_unit ) {
140 case 'in':
141 $dimension *= 0.3937;
142 break;
143 case 'm':
144 $dimension *= 0.01;
145 break;
146 case 'mm':
147 $dimension *= 10;
148 break;
149 case 'yd':
150 $dimension *= 0.010936133;
151 break;
152 }
153 }
154
155 return ( $dimension < 0 ) ? 0 : $dimension;
156 }
157
158 /**
159 * Normalise weights, unify to kg then convert to wanted unit value.
160 *
161 * Usage:
162 * wc_get_weight(55, 'kg');
163 * wc_get_weight(55, 'kg', 'lbs');
164 *
165 * @param int|float $weight Weight.
166 * @param string $to_unit Unit to convert to.
167 * Options: 'g', 'kg', 'lbs', 'oz'.
168 * @param string $from_unit Unit to convert from.
169 * Defaults to ''.
170 * Options: 'g', 'kg', 'lbs', 'oz'.
171 * @return float
172 */
173 function wc_get_weight( $weight, $to_unit, $from_unit = '' ) {
174 $weight = (float) $weight;
175 $to_unit = strtolower( $to_unit );
176
177 if ( empty( $from_unit ) ) {
178 $from_unit = strtolower( get_option( 'woocommerce_weight_unit' ) );
179 }
180
181 // Unify all units to kg first.
182 if ( $from_unit !== $to_unit ) {
183 switch ( $from_unit ) {
184 case 'g':
185 $weight *= 0.001;
186 break;
187 case 'lbs':
188 $weight *= 0.453592;
189 break;
190 case 'oz':
191 $weight *= 0.0283495;
192 break;
193 }
194
195 // Output desired unit.
196 switch ( $to_unit ) {
197 case 'g':
198 $weight *= 1000;
199 break;
200 case 'lbs':
201 $weight *= 2.20462;
202 break;
203 case 'oz':
204 $weight *= 35.274;
205 break;
206 }
207 }
208
209 return ( $weight < 0 ) ? 0 : $weight;
210 }
211
212 /**
213 * Trim trailing zeros off prices.
214 *
215 * @param string|float|int $price Price.
216 * @return string
217 */
218 function wc_trim_zeros( $price ) {
219 return preg_replace( '/' . preg_quote( wc_get_price_decimal_separator(), '/' ) . '0++$/', '', $price );
220 }
221
222 /**
223 * Round a tax amount.
224 *
225 * @param double $value Amount to round.
226 * @param int $precision DP to round. Defaults to wc_get_price_decimals.
227 * @return float
228 */
229 function wc_round_tax_total( $value, $precision = null ) {
230 $precision = is_null( $precision ) ? wc_get_price_decimals() : intval( $precision );
231
232 if ( version_compare( PHP_VERSION, '5.3.0', '>=' ) ) {
233 $rounded_tax = NumberUtil::round( $value, $precision, wc_get_tax_rounding_mode() ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.round_modeFound
234 } elseif ( 2 === wc_get_tax_rounding_mode() ) {
235 $rounded_tax = wc_legacy_round_half_down( $value, $precision );
236 } else {
237 $rounded_tax = NumberUtil::round( $value, $precision );
238 }
239
240 return apply_filters( 'wc_round_tax_total', $rounded_tax, $value, $precision, WC_TAX_ROUNDING_MODE );
241 }
242
243 /**
244 * Round half down in PHP 5.2.
245 *
246 * @since 3.2.6
247 * @param float $value Value to round.
248 * @param int $precision Precision to round down to.
249 * @return float
250 */
251 function wc_legacy_round_half_down( $value, $precision ) {
252 $value = wc_float_to_string( $value );
253
254 if ( false !== strstr( $value, '.' ) ) {
255 $value = explode( '.', $value );
256
257 if ( strlen( $value[1] ) > $precision && substr( $value[1], -1 ) === '5' ) {
258 $value[1] = substr( $value[1], 0, -1 ) . '4';
259 }
260
261 $value = implode( '.', $value );
262 }
263
264 return NumberUtil::round( floatval( $value ), $precision );
265 }
266
267 /**
268 * Make a refund total negative.
269 *
270 * @param float $amount Refunded amount.
271 *
272 * @return float
273 */
274 function wc_format_refund_total( $amount ) {
275 return $amount * -1;
276 }
277
278 /**
279 * Format decimal numbers ready for DB storage.
280 *
281 * Sanitize, optionally remove decimals, and optionally round + trim off zeros.
282 *
283 * This function does not remove thousands - this should be done before passing a value to the function.
284 *
285 * @param float|string $number Expects either a float or a string with a decimal separator only (no thousands).
286 * @param mixed $dp number Number of decimal points to use, blank to use woocommerce_price_num_decimals, or false to avoid all rounding.
287 * @param bool $trim_zeros From end of string.
288 * @return string
289 */
290 function wc_format_decimal( $number, $dp = false, $trim_zeros = false ) {
291 $locale = localeconv();
292 $decimals = array( wc_get_price_decimal_separator(), $locale['decimal_point'], $locale['mon_decimal_point'] );
293
294 // Remove locale from string.
295 if ( ! is_float( $number ) ) {
296 $number = str_replace( $decimals, '.', $number );
297
298 // Convert multiple dots to just one.
299 $number = preg_replace( '/\.(?![^.]+$)|[^0-9.-]/', '', wc_clean( $number ) );
300 }
301
302 if ( false !== $dp ) {
303 $dp = intval( '' === $dp ? wc_get_price_decimals() : $dp );
304 $number = number_format( floatval( $number ), $dp, '.', '' );
305 } elseif ( is_float( $number ) ) {
306 // DP is false - don't use number format, just return a string using whatever is given. Remove scientific notation using sprintf.
307 $number = str_replace( $decimals, '.', sprintf( '%.' . wc_get_rounding_precision() . 'f', $number ) );
308 // We already had a float, so trailing zeros are not needed.
309 $trim_zeros = true;
310 }
311
312 if ( $trim_zeros && strstr( $number, '.' ) ) {
313 $number = rtrim( rtrim( $number, '0' ), '.' );
314 }
315
316 return $number;
317 }
318
319 /**
320 * Convert a float to a string without locale formatting which PHP adds when changing floats to strings.
321 *
322 * @param float $float Float value to format.
323 * @return string
324 */
325 function wc_float_to_string( $float ) {
326 if ( ! is_float( $float ) ) {
327 return $float;
328 }
329
330 $locale = localeconv();
331 $string = strval( $float );
332 $string = str_replace( $locale['decimal_point'], '.', $string );
333
334 return $string;
335 }
336
337 /**
338 * Format a price with WC Currency Locale settings.
339 *
340 * @param string $value Price to localize.
341 * @return string
342 */
343 function wc_format_localized_price( $value ) {
344 return apply_filters( 'woocommerce_format_localized_price', str_replace( '.', wc_get_price_decimal_separator(), strval( $value ) ), $value );
345 }
346
347 /**
348 * Format a decimal with the decimal separator for prices or PHP Locale settings.
349 *
350 * @param string $value Decimal to localize.
351 * @return string
352 */
353 function wc_format_localized_decimal( $value ) {
354 $locale = localeconv();
355 $decimal_point = isset( $locale['decimal_point'] ) ? $locale['decimal_point'] : '.';
356 $decimal = ( ! empty( wc_get_price_decimal_separator() ) ) ? wc_get_price_decimal_separator() : $decimal_point;
357 return apply_filters( 'woocommerce_format_localized_decimal', str_replace( '.', $decimal, strval( $value ) ), $value );
358 }
359
360 /**
361 * Format a coupon code.
362 *
363 * @since 3.0.0
364 * @param string $value Coupon code to format.
365 * @return string
366 */
367 function wc_format_coupon_code( $value ) {
368 return apply_filters( 'woocommerce_coupon_code', $value );
369 }
370
371 /**
372 * Sanitize a coupon code.
373 *
374 * Uses sanitize_post_field since coupon codes are stored as
375 * post_titles - the sanitization and escaping must match.
376 *
377 * @since 3.6.0
378 * @param string $value Coupon code to format.
379 * @return string
380 */
381 function wc_sanitize_coupon_code( $value ) {
382 return wp_filter_kses( sanitize_post_field( 'post_title', $value, 0, 'db' ) );
383 }
384
385 /**
386 * Clean variables using sanitize_text_field. Arrays are cleaned recursively.
387 * Non-scalar values are ignored.
388 *
389 * @param string|array $var Data to sanitize.
390 * @return string|array
391 */
392 function wc_clean( $var ) {
393 if ( is_array( $var ) ) {
394 return array_map( 'wc_clean', $var );
395 } else {
396 return is_scalar( $var ) ? sanitize_text_field( $var ) : $var;
397 }
398 }
399
400 /**
401 * Function wp_check_invalid_utf8 with recursive array support.
402 *
403 * @param string|array $var Data to sanitize.
404 * @return string|array
405 */
406 function wc_check_invalid_utf8( $var ) {
407 if ( is_array( $var ) ) {
408 return array_map( 'wc_check_invalid_utf8', $var );
409 } else {
410 return wp_check_invalid_utf8( $var );
411 }
412 }
413
414 /**
415 * Run wc_clean over posted textarea but maintain line breaks.
416 *
417 * @since 3.0.0
418 * @param string $var Data to sanitize.
419 * @return string
420 */
421 function wc_sanitize_textarea( $var ) {
422 return implode( "\n", array_map( 'wc_clean', explode( "\n", $var ) ) );
423 }
424
425 /**
426 * Sanitize a string destined to be a tooltip.
427 *
428 * @since 2.3.10 Tooltips are encoded with htmlspecialchars to prevent XSS. Should not be used in conjunction with esc_attr()
429 * @param string $var Data to sanitize.
430 * @return string
431 */
432 function wc_sanitize_tooltip( $var ) {
433 return htmlspecialchars(
434 wp_kses(
435 html_entity_decode( $var ),
436 array(
437 'br' => array(),
438 'em' => array(),
439 'strong' => array(),
440 'small' => array(),
441 'span' => array(),
442 'ul' => array(),
443 'li' => array(),
444 'ol' => array(),
445 'p' => array(),
446 )
447 )
448 );
449 }
450
451 /**
452 * Merge two arrays.
453 *
454 * @param array $a1 First array to merge.
455 * @param array $a2 Second array to merge.
456 * @return array
457 */
458 function wc_array_overlay( $a1, $a2 ) {
459 foreach ( $a1 as $k => $v ) {
460 if ( ! array_key_exists( $k, $a2 ) ) {
461 continue;
462 }
463 if ( is_array( $v ) && is_array( $a2[ $k ] ) ) {
464 $a1[ $k ] = wc_array_overlay( $v, $a2[ $k ] );
465 } else {
466 $a1[ $k ] = $a2[ $k ];
467 }
468 }
469 return $a1;
470 }
471
472 /**
473 * Formats a stock amount by running it through a filter.
474 *
475 * @param int|float $amount Stock amount.
476 * @return int|float
477 */
478 function wc_stock_amount( $amount ) {
479 return apply_filters( 'woocommerce_stock_amount', $amount );
480 }
481
482 /**
483 * Get the price format depending on the currency position.
484 *
485 * @return string
486 */
487 function get_woocommerce_price_format() {
488 $currency_pos = get_option( 'woocommerce_currency_pos' );
489 $format = '%1$s%2$s';
490
491 switch ( $currency_pos ) {
492 case 'left':
493 $format = '%1$s%2$s';
494 break;
495 case 'right':
496 $format = '%2$s%1$s';
497 break;
498 case 'left_space':
499 $format = '%1$s&nbsp;%2$s';
500 break;
501 case 'right_space':
502 $format = '%2$s&nbsp;%1$s';
503 break;
504 }
505
506 return apply_filters( 'woocommerce_price_format', $format, $currency_pos );
507 }
508
509 /**
510 * Return the thousand separator for prices.
511 *
512 * @since 2.3
513 * @return string
514 */
515 function wc_get_price_thousand_separator() {
516 return stripslashes( apply_filters( 'wc_get_price_thousand_separator', get_option( 'woocommerce_price_thousand_sep' ) ) );
517 }
518
519 /**
520 * Return the decimal separator for prices.
521 *
522 * @since 2.3
523 * @return string
524 */
525 function wc_get_price_decimal_separator() {
526 $separator = apply_filters( 'wc_get_price_decimal_separator', get_option( 'woocommerce_price_decimal_sep' ) );
527 return $separator ? stripslashes( $separator ) : '.';
528 }
529
530 /**
531 * Return the number of decimals after the decimal point.
532 *
533 * @since 2.3
534 * @return int
535 */
536 function wc_get_price_decimals() {
537 return absint( apply_filters( 'wc_get_price_decimals', get_option( 'woocommerce_price_num_decimals', 2 ) ) );
538 }
539
540 /**
541 * Format the price with a currency symbol.
542 *
543 * @param float $price Raw price.
544 * @param array $args Arguments to format a price {
545 * Array of arguments.
546 * Defaults to empty array.
547 *
548 * @type bool $ex_tax_label Adds exclude tax label.
549 * Defaults to false.
550 * @type string $currency Currency code.
551 * Defaults to empty string (Use the result from get_woocommerce_currency()).
552 * @type string $decimal_separator Decimal separator.
553 * Defaults the result of wc_get_price_decimal_separator().
554 * @type string $thousand_separator Thousand separator.
555 * Defaults the result of wc_get_price_thousand_separator().
556 * @type string $decimals Number of decimals.
557 * Defaults the result of wc_get_price_decimals().
558 * @type string $price_format Price format depending on the currency position.
559 * Defaults the result of get_woocommerce_price_format().
560 * }
561 * @return string
562 */
563 function wc_price( $price, $args = array() ) {
564 $args = apply_filters(
565 'wc_price_args',
566 wp_parse_args(
567 $args,
568 array(
569 'ex_tax_label' => false,
570 'currency' => '',
571 'decimal_separator' => wc_get_price_decimal_separator(),
572 'thousand_separator' => wc_get_price_thousand_separator(),
573 'decimals' => wc_get_price_decimals(),
574 'price_format' => get_woocommerce_price_format(),
575 )
576 )
577 );
578
579 $original_price = $price;
580
581 // Convert to float to avoid issues on PHP 8.
582 $price = (float) $price;
583
584 $unformatted_price = $price;
585 $negative = $price < 0;
586
587 /**
588 * Filter raw price.
589 *
590 * @param float $raw_price Raw price.
591 * @param float|string $original_price Original price as float, or empty string. Since 5.0.0.
592 */
593 $price = apply_filters( 'raw_woocommerce_price', $negative ? $price * -1 : $price, $original_price );
594
595 /**
596 * Filter formatted price.
597 *
598 * @param float $formatted_price Formatted price.
599 * @param float $price Unformatted price.
600 * @param int $decimals Number of decimals.
601 * @param string $decimal_separator Decimal separator.
602 * @param string $thousand_separator Thousand separator.
603 * @param float|string $original_price Original price as float, or empty string. Since 5.0.0.
604 */
605 $price = apply_filters( 'formatted_woocommerce_price', number_format( $price, $args['decimals'], $args['decimal_separator'], $args['thousand_separator'] ), $price, $args['decimals'], $args['decimal_separator'], $args['thousand_separator'], $original_price );
606
607 if ( apply_filters( 'woocommerce_price_trim_zeros', false ) && $args['decimals'] > 0 ) {
608 $price = wc_trim_zeros( $price );
609 }
610
611 $formatted_price = ( $negative ? '-' : '' ) . sprintf( $args['price_format'], '<span class="woocommerce-Price-currencySymbol">' . get_woocommerce_currency_symbol( $args['currency'] ) . '</span>', $price );
612 $return = '<span class="woocommerce-Price-amount amount"><bdi>' . $formatted_price . '</bdi></span>';
613
614 if ( $args['ex_tax_label'] && wc_tax_enabled() ) {
615 $return .= ' <small class="woocommerce-Price-taxLabel tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
616 }
617
618 /**
619 * Filters the string of price markup.
620 *
621 * @param string $return Price HTML markup.
622 * @param string $price Formatted price.
623 * @param array $args Pass on the args.
624 * @param float $unformatted_price Price as float to allow plugins custom formatting. Since 3.2.0.
625 * @param float|string $original_price Original price as float, or empty string. Since 5.0.0.
626 */
627 return apply_filters( 'wc_price', $return, $price, $args, $unformatted_price, $original_price );
628 }
629
630 /**
631 * Notation to numbers.
632 *
633 * This function transforms the php.ini notation for numbers (like '2M') to an integer.
634 *
635 * @param string $size Size value.
636 * @return int
637 */
638 function wc_let_to_num( $size ) {
639 $l = substr( $size, -1 );
640 $ret = (int) substr( $size, 0, -1 );
641 switch ( strtoupper( $l ) ) {
642 case 'P':
643 $ret *= 1024;
644 // No break.
645 case 'T':
646 $ret *= 1024;
647 // No break.
648 case 'G':
649 $ret *= 1024;
650 // No break.
651 case 'M':
652 $ret *= 1024;
653 // No break.
654 case 'K':
655 $ret *= 1024;
656 // No break.
657 }
658 return $ret;
659 }
660
661 /**
662 * WooCommerce Date Format - Allows to change date format for everything WooCommerce.
663 *
664 * @return string
665 */
666 function wc_date_format() {
667 $date_format = get_option( 'date_format' );
668 if ( empty( $date_format ) ) {
669 // Return default date format if the option is empty.
670 $date_format = 'F j, Y';
671 }
672 return apply_filters( 'woocommerce_date_format', $date_format );
673 }
674
675 /**
676 * WooCommerce Time Format - Allows to change time format for everything WooCommerce.
677 *
678 * @return string
679 */
680 function wc_time_format() {
681 $time_format = get_option( 'time_format' );
682 if ( empty( $time_format ) ) {
683 // Return default time format if the option is empty.
684 $time_format = 'g:i a';
685 }
686 return apply_filters( 'woocommerce_time_format', $time_format );
687 }
688
689 /**
690 * Convert mysql datetime to PHP timestamp, forcing UTC. Wrapper for strtotime.
691 *
692 * Based on wcs_strtotime_dark_knight() from WC Subscriptions by Prospress.
693 *
694 * @since 3.0.0
695 * @param string $time_string Time string.
696 * @param int|null $from_timestamp Timestamp to convert from.
697 * @return int
698 */
699 function wc_string_to_timestamp( $time_string, $from_timestamp = null ) {
700 $original_timezone = date_default_timezone_get();
701
702 // @codingStandardsIgnoreStart
703 date_default_timezone_set( 'UTC' );
704
705 if ( null === $from_timestamp ) {
706 $next_timestamp = strtotime( $time_string );
707 } else {
708 $next_timestamp = strtotime( $time_string, $from_timestamp );
709 }
710
711 date_default_timezone_set( $original_timezone );
712 // @codingStandardsIgnoreEnd
713
714 return $next_timestamp;
715 }
716
717 /**
718 * Convert a date string to a WC_DateTime.
719 *
720 * @since 3.1.0
721 * @param string $time_string Time string.
722 * @return WC_DateTime
723 */
724 function wc_string_to_datetime( $time_string ) {
725 // Strings are defined in local WP timezone. Convert to UTC.
726 if ( 1 === preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|((-|\+)\d{2}:\d{2}))$/', $time_string, $date_bits ) ) {
727 $offset = ! empty( $date_bits[7] ) ? iso8601_timezone_to_offset( $date_bits[7] ) : wc_timezone_offset();
728 $timestamp = gmmktime( $date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1] ) - $offset;
729 } else {
730 $timestamp = wc_string_to_timestamp( get_gmt_from_date( gmdate( 'Y-m-d H:i:s', wc_string_to_timestamp( $time_string ) ) ) );
731 }
732 $datetime = new WC_DateTime( "@{$timestamp}", new DateTimeZone( 'UTC' ) );
733
734 // Set local timezone or offset.
735 if ( get_option( 'timezone_string' ) ) {
736 $datetime->setTimezone( new DateTimeZone( wc_timezone_string() ) );
737 } else {
738 $datetime->set_utc_offset( wc_timezone_offset() );
739 }
740
741 return $datetime;
742 }
743
744 /**
745 * WooCommerce Timezone - helper to retrieve the timezone string for a site until.
746 * a WP core method exists (see https://core.trac.wordpress.org/ticket/24730).
747 *
748 * Adapted from https://secure.php.net/manual/en/function.timezone-name-from-abbr.php#89155.
749 *
750 * @since 2.1
751 * @return string PHP timezone string for the site
752 */
753 function wc_timezone_string() {
754 // Added in WordPress 5.3 Ref https://developer.wordpress.org/reference/functions/wp_timezone_string/.
755 if ( function_exists( 'wp_timezone_string' ) ) {
756 return wp_timezone_string();
757 }
758
759 // If site timezone string exists, return it.
760 $timezone = get_option( 'timezone_string' );
761 if ( $timezone ) {
762 return $timezone;
763 }
764
765 // Get UTC offset, if it isn't set then return UTC.
766 $utc_offset = floatval( get_option( 'gmt_offset', 0 ) );
767 if ( ! is_numeric( $utc_offset ) || 0.0 === $utc_offset ) {
768 return 'UTC';
769 }
770
771 // Adjust UTC offset from hours to seconds.
772 $utc_offset = (int) ( $utc_offset * 3600 );
773
774 // Attempt to guess the timezone string from the UTC offset.
775 $timezone = timezone_name_from_abbr( '', $utc_offset );
776 if ( $timezone ) {
777 return $timezone;
778 }
779
780 // Last try, guess timezone string manually.
781 foreach ( timezone_abbreviations_list() as $abbr ) {
782 foreach ( $abbr as $city ) {
783 // WordPress restrict the use of date(), since it's affected by timezone settings, but in this case is just what we need to guess the correct timezone.
784 if ( (bool) date( 'I' ) === (bool) $city['dst'] && $city['timezone_id'] && intval( $city['offset'] ) === $utc_offset ) { // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
785 return $city['timezone_id'];
786 }
787 }
788 }
789
790 // Fallback to UTC.
791 return 'UTC';
792 }
793
794 /**
795 * Get timezone offset in seconds.
796 *
797 * @since 3.0.0
798 * @return float
799 */
800 function wc_timezone_offset() {
801 $timezone = get_option( 'timezone_string' );
802
803 if ( $timezone ) {
804 $timezone_object = new DateTimeZone( $timezone );
805 return $timezone_object->getOffset( new DateTime( 'now' ) );
806 } else {
807 return floatval( get_option( 'gmt_offset', 0 ) ) * HOUR_IN_SECONDS;
808 }
809 }
810
811 /**
812 * Callback which can flatten post meta (gets the first value if it's an array).
813 *
814 * @since 3.0.0
815 * @param array $value Value to flatten.
816 * @return mixed
817 */
818 function wc_flatten_meta_callback( $value ) {
819 return is_array( $value ) ? current( $value ) : $value;
820 }
821
822 if ( ! function_exists( 'wc_rgb_from_hex' ) ) {
823
824 /**
825 * Convert RGB to HEX.
826 *
827 * @param mixed $color Color.
828 *
829 * @return array
830 */
831 function wc_rgb_from_hex( $color ) {
832 $color = str_replace( '#', '', $color );
833 // Convert shorthand colors to full format, e.g. "FFF" -> "FFFFFF".
834 $color = preg_replace( '~^(.)(.)(.)$~', '$1$1$2$2$3$3', $color );
835
836 $rgb = array();
837 $rgb['R'] = hexdec( $color[0] . $color[1] );
838 $rgb['G'] = hexdec( $color[2] . $color[3] );
839 $rgb['B'] = hexdec( $color[4] . $color[5] );
840
841 return $rgb;
842 }
843 }
844
845 if ( ! function_exists( 'wc_hex_darker' ) ) {
846
847 /**
848 * Make HEX color darker.
849 *
850 * @param mixed $color Color.
851 * @param int $factor Darker factor.
852 * Defaults to 30.
853 * @return string
854 */
855 function wc_hex_darker( $color, $factor = 30 ) {
856 $base = wc_rgb_from_hex( $color );
857 $color = '#';
858
859 foreach ( $base as $k => $v ) {
860 $amount = $v / 100;
861 $amount = NumberUtil::round( $amount * $factor );
862 $new_decimal = $v - $amount;
863
864 $new_hex_component = dechex( $new_decimal );
865 if ( strlen( $new_hex_component ) < 2 ) {
866 $new_hex_component = '0' . $new_hex_component;
867 }
868 $color .= $new_hex_component;
869 }
870
871 return $color;
872 }
873 }
874
875 if ( ! function_exists( 'wc_hex_lighter' ) ) {
876
877 /**
878 * Make HEX color lighter.
879 *
880 * @param mixed $color Color.
881 * @param int $factor Lighter factor.
882 * Defaults to 30.
883 * @return string
884 */
885 function wc_hex_lighter( $color, $factor = 30 ) {
886 $base = wc_rgb_from_hex( $color );
887 $color = '#';
888
889 foreach ( $base as $k => $v ) {
890 $amount = 255 - $v;
891 $amount = $amount / 100;
892 $amount = NumberUtil::round( $amount * $factor );
893 $new_decimal = $v + $amount;
894
895 $new_hex_component = dechex( $new_decimal );
896 if ( strlen( $new_hex_component ) < 2 ) {
897 $new_hex_component = '0' . $new_hex_component;
898 }
899 $color .= $new_hex_component;
900 }
901
902 return $color;
903 }
904 }
905
906 if ( ! function_exists( 'wc_hex_is_light' ) ) {
907
908 /**
909 * Determine whether a hex color is light.
910 *
911 * @param mixed $color Color.
912 * @return bool True if a light color.
913 */
914 function wc_hex_is_light( $color ) {
915 $hex = str_replace( '#', '', $color );
916
917 $c_r = hexdec( substr( $hex, 0, 2 ) );
918 $c_g = hexdec( substr( $hex, 2, 2 ) );
919 $c_b = hexdec( substr( $hex, 4, 2 ) );
920
921 $brightness = ( ( $c_r * 299 ) + ( $c_g * 587 ) + ( $c_b * 114 ) ) / 1000;
922
923 return $brightness > 155;
924 }
925 }
926
927 if ( ! function_exists( 'wc_light_or_dark' ) ) {
928
929 /**
930 * Detect if we should use a light or dark color on a background color.
931 *
932 * @param mixed $color Color.
933 * @param string $dark Darkest reference.
934 * Defaults to '#000000'.
935 * @param string $light Lightest reference.
936 * Defaults to '#FFFFFF'.
937 * @return string
938 */
939 function wc_light_or_dark( $color, $dark = '#000000', $light = '#FFFFFF' ) {
940 return wc_hex_is_light( $color ) ? $dark : $light;
941 }
942 }
943
944 if ( ! function_exists( 'wc_format_hex' ) ) {
945
946 /**
947 * Format string as hex.
948 *
949 * @param string $hex HEX color.
950 * @return string|null
951 */
952 function wc_format_hex( $hex ) {
953 $hex = trim( str_replace( '#', '', $hex ?? '' ) );
954
955 if ( strlen( $hex ) === 3 ) {
956 $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
957 }
958
959 return $hex ? '#' . $hex : null;
960 }
961 }
962
963 /**
964 * Format the postcode according to the country and length of the postcode.
965 *
966 * @param string $postcode Unformatted postcode.
967 * @param string $country Base country.
968 * @return string
969 */
970 function wc_format_postcode( $postcode, $country ) {
971 $postcode = wc_normalize_postcode( $postcode );
972
973 switch ( $country ) {
974 case 'CA':
975 case 'GB':
976 $postcode = substr_replace( $postcode, ' ', -3, 0 );
977 break;
978 case 'IE':
979 $postcode = substr_replace( $postcode, ' ', 3, 0 );
980 break;
981 case 'BR':
982 case 'PL':
983 $postcode = substr_replace( $postcode, '-', -3, 0 );
984 break;
985 case 'JP':
986 $postcode = substr_replace( $postcode, '-', 3, 0 );
987 break;
988 case 'PT':
989 $postcode = substr_replace( $postcode, '-', 4, 0 );
990 break;
991 case 'PR':
992 case 'US':
993 $postcode = rtrim( substr_replace( $postcode, '-', 5, 0 ), '-' );
994 break;
995 case 'NL':
996 $postcode = substr_replace( $postcode, ' ', 4, 0 );
997 break;
998 case 'LV':
999 if ( preg_match( '/(?:LV)?-?(\d+)/i', $postcode, $matches ) ) {
1000 $postcode = count( $matches ) >= 2 ? "LV-$matches[1]" : $postcode;
1001 }
1002 break;
1003 }
1004
1005 return apply_filters( 'woocommerce_format_postcode', trim( $postcode ), $country );
1006 }
1007
1008 /**
1009 * Normalize postcodes.
1010 *
1011 * Remove spaces and convert characters to uppercase.
1012 *
1013 * @since 2.6.0
1014 * @param string $postcode Postcode.
1015 * @return string
1016 */
1017 function wc_normalize_postcode( $postcode ) {
1018 return preg_replace( '/[\s\-]/', '', trim( wc_strtoupper( $postcode ) ) );
1019 }
1020
1021 /**
1022 * Format phone numbers.
1023 *
1024 * @param string $phone Phone number.
1025 * @return string
1026 */
1027 function wc_format_phone_number( $phone ) {
1028 if ( ! WC_Validation::is_phone( $phone ) ) {
1029 return '';
1030 }
1031 return preg_replace( '/[^0-9\+\-\(\)\s]/', '-', preg_replace( '/[\x00-\x1F\x7F-\xFF]/', '', $phone ) );
1032 }
1033
1034 /**
1035 * Sanitize phone number.
1036 * Allows only numbers and "+" (plus sign).
1037 *
1038 * @since 3.6.0
1039 * @param string $phone Phone number.
1040 * @return string
1041 */
1042 function wc_sanitize_phone_number( $phone ) {
1043 return preg_replace( '/[^\d+]/', '', $phone );
1044 }
1045
1046 /**
1047 * Wrapper for mb_strtoupper which see's if supported first.
1048 *
1049 * @since 3.1.0
1050 * @param string $string String to format.
1051 * @return string
1052 */
1053 function wc_strtoupper( $string ) {
1054 return function_exists( 'mb_strtoupper' ) ? mb_strtoupper( $string ) : strtoupper( $string );
1055 }
1056
1057 /**
1058 * Make a string lowercase.
1059 * Try to use mb_strtolower() when available.
1060 *
1061 * @since 2.3
1062 * @param string $string String to format.
1063 * @return string
1064 */
1065 function wc_strtolower( $string ) {
1066 return function_exists( 'mb_strtolower' ) ? mb_strtolower( $string ) : strtolower( $string );
1067 }
1068
1069 /**
1070 * Trim a string and append a suffix.
1071 *
1072 * @param string $string String to trim.
1073 * @param integer $chars Amount of characters.
1074 * Defaults to 200.
1075 * @param string $suffix Suffix.
1076 * Defaults to '...'.
1077 * @return string
1078 */
1079 function wc_trim_string( $string, $chars = 200, $suffix = '...' ) {
1080 if ( strlen( $string ) > $chars ) {
1081 if ( function_exists( 'mb_substr' ) ) {
1082 $string = mb_substr( $string, 0, ( $chars - mb_strlen( $suffix ) ) ) . $suffix;
1083 } else {
1084 $string = substr( $string, 0, ( $chars - strlen( $suffix ) ) ) . $suffix;
1085 }
1086 }
1087 return $string;
1088 }
1089
1090 /**
1091 * Format content to display shortcodes.
1092 *
1093 * @since 2.3.0
1094 * @param string $raw_string Raw string.
1095 * @return string
1096 */
1097 function wc_format_content( $raw_string ) {
1098 return apply_filters( 'woocommerce_format_content', apply_filters( 'woocommerce_short_description', $raw_string ), $raw_string );
1099 }
1100
1101 /**
1102 * Format product short description.
1103 * Adds support for Jetpack Markdown.
1104 *
1105 * @codeCoverageIgnore
1106 * @since 2.4.0
1107 * @param string $content Product short description.
1108 * @return string
1109 */
1110 function wc_format_product_short_description( $content ) {
1111 // Add support for Jetpack Markdown.
1112 if ( class_exists( 'WPCom_Markdown' ) ) {
1113 $markdown = WPCom_Markdown::get_instance();
1114
1115 return wpautop(
1116 $markdown->transform(
1117 $content,
1118 array(
1119 'unslash' => false,
1120 )
1121 )
1122 );
1123 }
1124
1125 return $content;
1126 }
1127
1128 /**
1129 * Formats curency symbols when saved in settings.
1130 *
1131 * @codeCoverageIgnore
1132 * @param string $value Option value.
1133 * @param array $option Option name.
1134 * @param string $raw_value Raw value.
1135 * @return string
1136 */
1137 function wc_format_option_price_separators( $value, $option, $raw_value ) {
1138 return wp_kses_post( $raw_value );
1139 }
1140 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_price_decimal_sep', 'wc_format_option_price_separators', 10, 3 );
1141 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_price_thousand_sep', 'wc_format_option_price_separators', 10, 3 );
1142
1143 /**
1144 * Formats decimals when saved in settings.
1145 *
1146 * @codeCoverageIgnore
1147 * @param string $value Option value.
1148 * @param array $option Option name.
1149 * @param string $raw_value Raw value.
1150 * @return string
1151 */
1152 function wc_format_option_price_num_decimals( $value, $option, $raw_value ) {
1153 return is_null( $raw_value ) ? 2 : absint( $raw_value );
1154 }
1155 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_price_num_decimals', 'wc_format_option_price_num_decimals', 10, 3 );
1156
1157 /**
1158 * Formats hold stock option and sets cron event up.
1159 *
1160 * @codeCoverageIgnore
1161 * @param string $value Option value.
1162 * @param array $option Option name.
1163 * @param string $raw_value Raw value.
1164 * @return string
1165 */
1166 function wc_format_option_hold_stock_minutes( $value, $option, $raw_value ) {
1167 $value = ! empty( $raw_value ) ? absint( $raw_value ) : ''; // Allow > 0 or set to ''.
1168
1169 wp_clear_scheduled_hook( 'woocommerce_cancel_unpaid_orders' );
1170
1171 if ( '' !== $value ) {
1172 $cancel_unpaid_interval = apply_filters( 'woocommerce_cancel_unpaid_orders_interval_minutes', absint( $value ) );
1173 wp_schedule_single_event( time() + ( absint( $cancel_unpaid_interval ) * 60 ), 'woocommerce_cancel_unpaid_orders' );
1174 }
1175
1176 return $value;
1177 }
1178 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_hold_stock_minutes', 'wc_format_option_hold_stock_minutes', 10, 3 );
1179
1180 /**
1181 * Sanitize terms from an attribute text based.
1182 *
1183 * @since 2.4.5
1184 * @param string $term Term value.
1185 * @return string
1186 */
1187 function wc_sanitize_term_text_based( $term ) {
1188 return trim( wp_strip_all_tags( wp_unslash( $term ) ) );
1189 }
1190
1191 if ( ! function_exists( 'wc_make_numeric_postcode' ) ) {
1192 /**
1193 * Make numeric postcode.
1194 *
1195 * Converts letters to numbers so we can do a simple range check on postcodes.
1196 * E.g. PE30 becomes 16050300 (P = 16, E = 05, 3 = 03, 0 = 00)
1197 *
1198 * @since 2.6.0
1199 * @param string $postcode Regular postcode.
1200 * @return string
1201 */
1202 function wc_make_numeric_postcode( $postcode ) {
1203 $postcode = str_replace( array( ' ', '-' ), '', $postcode );
1204 $postcode_length = strlen( $postcode );
1205 $letters_to_numbers = array_merge( array( 0 ), range( 'A', 'Z' ) );
1206 $letters_to_numbers = array_flip( $letters_to_numbers );
1207 $numeric_postcode = '';
1208
1209 for ( $i = 0; $i < $postcode_length; $i ++ ) {
1210 if ( is_numeric( $postcode[ $i ] ) ) {
1211 $numeric_postcode .= str_pad( $postcode[ $i ], 2, '0', STR_PAD_LEFT );
1212 } elseif ( isset( $letters_to_numbers[ $postcode[ $i ] ] ) ) {
1213 $numeric_postcode .= str_pad( $letters_to_numbers[ $postcode[ $i ] ], 2, '0', STR_PAD_LEFT );
1214 } else {
1215 $numeric_postcode .= '00';
1216 }
1217 }
1218
1219 return $numeric_postcode;
1220 }
1221 }
1222
1223 /**
1224 * Format the stock amount ready for display based on settings.
1225 *
1226 * @since 3.0.0
1227 * @param WC_Product $product Product object for which the stock you need to format.
1228 * @return string
1229 */
1230 function wc_format_stock_for_display( $product ) {
1231 $display = __( 'In stock', 'woocommerce' );
1232 $stock_amount = $product->get_stock_quantity();
1233
1234 switch ( get_option( 'woocommerce_stock_format' ) ) {
1235 case 'low_amount':
1236 if ( $stock_amount <= wc_get_low_stock_amount( $product ) ) {
1237 /* translators: %s: stock amount */
1238 $display = sprintf( __( 'Only %s left in stock', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
1239 }
1240 break;
1241 case '':
1242 /* translators: %s: stock amount */
1243 $display = sprintf( __( '%s in stock', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
1244 break;
1245 }
1246
1247 if ( $product->backorders_allowed() && $product->backorders_require_notification() ) {
1248 $display .= ' ' . __( '(can be backordered)', 'woocommerce' );
1249 }
1250
1251 return $display;
1252 }
1253
1254 /**
1255 * Format the stock quantity ready for display.
1256 *
1257 * @since 3.0.0
1258 * @param int $stock_quantity Stock quantity.
1259 * @param WC_Product $product Product instance so that we can pass through the filters.
1260 * @return string
1261 */
1262 function wc_format_stock_quantity_for_display( $stock_quantity, $product ) {
1263 return apply_filters( 'woocommerce_format_stock_quantity', $stock_quantity, $product );
1264 }
1265
1266 /**
1267 * Format a sale price for display.
1268 *
1269 * @since 3.0.0
1270 * @param string $regular_price Regular price.
1271 * @param string $sale_price Sale price.
1272 * @return string
1273 */
1274 function wc_format_sale_price( $regular_price, $sale_price ) {
1275 $price = '<del aria-hidden="true">' . ( is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price ) . '</del> <ins>' . ( is_numeric( $sale_price ) ? wc_price( $sale_price ) : $sale_price ) . '</ins>';
1276 return apply_filters( 'woocommerce_format_sale_price', $price, $regular_price, $sale_price );
1277 }
1278
1279 /**
1280 * Format a price range for display.
1281 *
1282 * @param string $from Price from.
1283 * @param string $to Price to.
1284 * @return string
1285 */
1286 function wc_format_price_range( $from, $to ) {
1287 /* translators: 1: price from 2: price to */
1288 $price = sprintf( _x( '%1$s &ndash; %2$s', 'Price range: from-to', 'woocommerce' ), is_numeric( $from ) ? wc_price( $from ) : $from, is_numeric( $to ) ? wc_price( $to ) : $to );
1289 return apply_filters( 'woocommerce_format_price_range', $price, $from, $to );
1290 }
1291
1292 /**
1293 * Format a weight for display.
1294 *
1295 * @since 3.0.0
1296 * @param float $weight Weight.
1297 * @return string
1298 */
1299 function wc_format_weight( $weight ) {
1300 $weight_string = wc_format_localized_decimal( $weight );
1301
1302 if ( ! empty( $weight_string ) ) {
1303 $weight_string .= ' ' . get_option( 'woocommerce_weight_unit' );
1304 } else {
1305 $weight_string = __( 'N/A', 'woocommerce' );
1306 }
1307
1308 return apply_filters( 'woocommerce_format_weight', $weight_string, $weight );
1309 }
1310
1311 /**
1312 * Format dimensions for display.
1313 *
1314 * @since 3.0.0
1315 * @param array $dimensions Array of dimensions.
1316 * @return string
1317 */
1318 function wc_format_dimensions( $dimensions ) {
1319 $dimension_string = implode( ' &times; ', array_filter( array_map( 'wc_format_localized_decimal', $dimensions ) ) );
1320
1321 if ( ! empty( $dimension_string ) ) {
1322 $dimension_string .= ' ' . get_option( 'woocommerce_dimension_unit' );
1323 } else {
1324 $dimension_string = __( 'N/A', 'woocommerce' );
1325 }
1326
1327 return apply_filters( 'woocommerce_format_dimensions', $dimension_string, $dimensions );
1328 }
1329
1330 /**
1331 * Format a date for output.
1332 *
1333 * @since 3.0.0
1334 * @param WC_DateTime $date Instance of WC_DateTime.
1335 * @param string $format Data format.
1336 * Defaults to the wc_date_format function if not set.
1337 * @return string
1338 */
1339 function wc_format_datetime( $date, $format = '' ) {
1340 if ( ! $format ) {
1341 $format = wc_date_format();
1342 }
1343 if ( ! is_a( $date, 'WC_DateTime' ) ) {
1344 return '';
1345 }
1346 return $date->date_i18n( $format );
1347 }
1348
1349 /**
1350 * Process oEmbeds.
1351 *
1352 * @since 3.1.0
1353 * @param string $content Content.
1354 * @return string
1355 */
1356 function wc_do_oembeds( $content ) {
1357 global $wp_embed;
1358
1359 $content = $wp_embed->autoembed( $content );
1360
1361 return $content;
1362 }
1363
1364 /**
1365 * Get part of a string before :.
1366 *
1367 * Used for example in shipping methods ids where they take the format
1368 * method_id:instance_id
1369 *
1370 * @since 3.2.0
1371 * @param string $string String to extract.
1372 * @return string
1373 */
1374 function wc_get_string_before_colon( $string ) {
1375 return trim( current( explode( ':', (string) $string ) ) );
1376 }
1377
1378 /**
1379 * Array merge and sum function.
1380 *
1381 * Source: https://gist.github.com/Nickology/f700e319cbafab5eaedc
1382 *
1383 * @since 3.2.0
1384 * @return array
1385 */
1386 function wc_array_merge_recursive_numeric() {
1387 $arrays = func_get_args();
1388
1389 // If there's only one array, it's already merged.
1390 if ( 1 === count( $arrays ) ) {
1391 return $arrays[0];
1392 }
1393
1394 // Remove any items in $arrays that are NOT arrays.
1395 foreach ( $arrays as $key => $array ) {
1396 if ( ! is_array( $array ) ) {
1397 unset( $arrays[ $key ] );
1398 }
1399 }
1400
1401 // We start by setting the first array as our final array.
1402 // We will merge all other arrays with this one.
1403 $final = array_shift( $arrays );
1404
1405 foreach ( $arrays as $b ) {
1406 foreach ( $final as $key => $value ) {
1407 // If $key does not exist in $b, then it is unique and can be safely merged.
1408 if ( ! isset( $b[ $key ] ) ) {
1409 $final[ $key ] = $value;
1410 } else {
1411 // If $key is present in $b, then we need to merge and sum numeric values in both.
1412 if ( is_numeric( $value ) && is_numeric( $b[ $key ] ) ) {
1413 // If both values for these keys are numeric, we sum them.
1414 $final[ $key ] = $value + $b[ $key ];
1415 } elseif ( is_array( $value ) && is_array( $b[ $key ] ) ) {
1416 // If both values are arrays, we recursively call ourself.
1417 $final[ $key ] = wc_array_merge_recursive_numeric( $value, $b[ $key ] );
1418 } else {
1419 // If both keys exist but differ in type, then we cannot merge them.
1420 // In this scenario, we will $b's value for $key is used.
1421 $final[ $key ] = $b[ $key ];
1422 }
1423 }
1424 }
1425
1426 // Finally, we need to merge any keys that exist only in $b.
1427 foreach ( $b as $key => $value ) {
1428 if ( ! isset( $final[ $key ] ) ) {
1429 $final[ $key ] = $value;
1430 }
1431 }
1432 }
1433
1434 return $final;
1435 }
1436
1437 /**
1438 * Implode and escape HTML attributes for output.
1439 *
1440 * @since 3.3.0
1441 * @param array $raw_attributes Attribute name value pairs.
1442 * @return string
1443 */
1444 function wc_implode_html_attributes( $raw_attributes ) {
1445 $attributes = array();
1446 foreach ( $raw_attributes as $name => $value ) {
1447 $attributes[] = esc_attr( $name ) . '="' . esc_attr( $value ) . '"';
1448 }
1449 return implode( ' ', $attributes );
1450 }
1451
1452 /**
1453 * Escape JSON for use on HTML or attribute text nodes.
1454 *
1455 * @since 3.5.5
1456 * @param string $json JSON to escape.
1457 * @param bool $html True if escaping for HTML text node, false for attributes. Determines how quotes are handled.
1458 * @return string Escaped JSON.
1459 */
1460 function wc_esc_json( $json, $html = false ) {
1461 return _wp_specialchars(
1462 $json,
1463 $html ? ENT_NOQUOTES : ENT_QUOTES, // Escape quotes in attribute nodes only.
1464 'UTF-8', // json_encode() outputs UTF-8 (really just ASCII), not the blog's charset.
1465 true // Double escape entities: `&amp;` -> `&amp;amp;`.
1466 );
1467 }
1468
1469 /**
1470 * Parse a relative date option from the settings API into a standard format.
1471 *
1472 * @since 3.4.0
1473 * @param mixed $raw_value Value stored in DB.
1474 * @return array Nicely formatted array with number and unit values.
1475 */
1476 function wc_parse_relative_date_option( $raw_value ) {
1477 $periods = array(
1478 'days' => __( 'Day(s)', 'woocommerce' ),
1479 'weeks' => __( 'Week(s)', 'woocommerce' ),
1480 'months' => __( 'Month(s)', 'woocommerce' ),
1481 'years' => __( 'Year(s)', 'woocommerce' ),
1482 );
1483
1484 $value = wp_parse_args(
1485 (array) $raw_value,
1486 array(
1487 'number' => '',
1488 'unit' => 'days',
1489 )
1490 );
1491
1492 $value['number'] = ! empty( $value['number'] ) ? absint( $value['number'] ) : '';
1493
1494 if ( ! in_array( $value['unit'], array_keys( $periods ), true ) ) {
1495 $value['unit'] = 'days';
1496 }
1497
1498 return $value;
1499 }
1500
1501 /**
1502 * Format the endpoint slug, strip out anything not allowed in a url.
1503 *
1504 * @since 3.5.0
1505 * @param string $raw_value The raw value.
1506 * @return string
1507 */
1508 function wc_sanitize_endpoint_slug( $raw_value ) {
1509 return sanitize_title( $raw_value );
1510 }
1511 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_checkout_pay_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1512 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_checkout_order_received_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1513 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_add_payment_method_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1514 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_delete_payment_method_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1515 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_set_default_payment_method_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1516 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_orders_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1517 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_view_order_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1518 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_downloads_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1519 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_edit_account_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1520 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_edit_address_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1521 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_payment_methods_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1522 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_lost_password_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1523 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_logout_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1524