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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 5 years ago admin 5 years ago blocks 5 years ago cli 5 years ago customizer 5 years ago data-stores 5 years ago emails 5 years ago export 5 years ago gateways 5 years ago import 5 years ago integrations 5 years ago interfaces 5 years ago legacy 5 years ago libraries 6 years ago log-handlers 5 years ago payment-tokens 5 years ago queue 5 years ago rest-api 5 years ago shipping 5 years ago shortcodes 5 years ago theme-support 5 years ago tracks 5 years ago traits 5 years ago walkers 5 years ago wccom-site 5 years ago widgets 5 years ago class-wc-ajax.php 5 years ago class-wc-api.php 5 years ago class-wc-auth.php 5 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 5 years ago class-wc-cart-fees.php 5 years ago class-wc-cart-session.php 5 years ago class-wc-cart-totals.php 5 years ago class-wc-cart.php 5 years ago class-wc-checkout.php 5 years ago class-wc-cli.php 8 years ago class-wc-comments.php 5 years ago class-wc-countries.php 5 years ago class-wc-coupon.php 5 years ago class-wc-customer-download-log.php 5 years ago class-wc-customer-download.php 5 years ago class-wc-customer.php 5 years ago class-wc-data-exception.php 8 years ago class-wc-data-store.php 6 years ago class-wc-datetime.php 5 years ago class-wc-deprecated-action-hooks.php 8 years ago class-wc-deprecated-filter-hooks.php 7 years ago class-wc-discounts.php 5 years ago class-wc-download-handler.php 5 years ago class-wc-emails.php 5 years ago class-wc-embed.php 5 years ago class-wc-form-handler.php 5 years ago class-wc-frontend-scripts.php 5 years ago class-wc-geo-ip.php 5 years ago class-wc-geolite-integration.php 6 years ago class-wc-geolocation.php 5 years ago class-wc-https.php 5 years ago class-wc-install.php 5 years ago class-wc-integrations.php 5 years ago class-wc-log-levels.php 5 years ago class-wc-logger.php 5 years ago class-wc-meta-data.php 7 years ago class-wc-order-factory.php 5 years ago class-wc-order-item-coupon.php 5 years ago class-wc-order-item-fee.php 5 years ago class-wc-order-item-meta.php 5 years ago class-wc-order-item-product.php 5 years ago class-wc-order-item-shipping.php 5 years ago class-wc-order-item-tax.php 5 years ago class-wc-order-item.php 5 years ago class-wc-order-query.php 5 years ago class-wc-order-refund.php 5 years ago class-wc-order.php 5 years ago class-wc-payment-gateways.php 5 years ago class-wc-payment-tokens.php 5 years ago class-wc-post-data.php 5 years ago class-wc-post-types.php 5 years ago class-wc-privacy-background-process.php 5 years ago class-wc-privacy-erasers.php 6 years ago class-wc-privacy-exporters.php 6 years ago class-wc-privacy.php 5 years ago class-wc-product-attribute.php 5 years ago class-wc-product-download.php 5 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 5 years ago class-wc-product-variation.php 5 years ago class-wc-query.php 5 years ago class-wc-rate-limiter.php 5 years ago class-wc-regenerate-images-request.php 5 years ago class-wc-regenerate-images.php 5 years ago class-wc-register-wp-admin-settings.php 5 years ago class-wc-rest-authentication.php 5 years ago class-wc-rest-exception.php 5 years ago class-wc-session-handler.php 5 years ago class-wc-shipping-rate.php 5 years ago class-wc-shipping-zone.php 5 years ago class-wc-shipping-zones.php 5 years ago class-wc-shipping.php 5 years ago class-wc-shortcodes.php 5 years ago class-wc-structured-data.php 5 years ago class-wc-tax.php 5 years ago class-wc-template-loader.php 5 years ago class-wc-tracker.php 5 years ago class-wc-validation.php 5 years ago class-wc-webhook.php 5 years ago class-woocommerce.php 5 years ago wc-account-functions.php 5 years ago wc-attribute-functions.php 5 years ago wc-cart-functions.php 5 years ago wc-conditional-functions.php 5 years ago wc-core-functions.php 5 years ago wc-coupon-functions.php 5 years ago wc-deprecated-functions.php 5 years ago wc-formatting-functions.php 5 years ago wc-notice-functions.php 5 years ago wc-order-functions.php 5 years ago wc-order-item-functions.php 5 years ago wc-page-functions.php 5 years ago wc-product-functions.php 5 years ago wc-rest-functions.php 5 years ago wc-stock-functions.php 5 years ago wc-template-functions.php 5 years ago wc-template-hooks.php 5 years ago wc-term-functions.php 5 years ago wc-update-functions.php 5 years ago wc-user-functions.php 5 years ago wc-webhook-functions.php 5 years ago wc-widget-functions.php 5 years ago
wc-formatting-functions.php
1517 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, 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 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 return apply_filters( 'woocommerce_format_localized_decimal', str_replace( '.', $locale['decimal_point'], strval( $value ) ), $value );
356 }
357
358 /**
359 * Format a coupon code.
360 *
361 * @since 3.0.0
362 * @param string $value Coupon code to format.
363 * @return string
364 */
365 function wc_format_coupon_code( $value ) {
366 return apply_filters( 'woocommerce_coupon_code', $value );
367 }
368
369 /**
370 * Sanitize a coupon code.
371 *
372 * Uses sanitize_post_field since coupon codes are stored as
373 * post_titles - the sanitization and escaping must match.
374 *
375 * @since 3.6.0
376 * @param string $value Coupon code to format.
377 * @return string
378 */
379 function wc_sanitize_coupon_code( $value ) {
380 return wp_filter_kses( sanitize_post_field( 'post_title', $value, 0, 'db' ) );
381 }
382
383 /**
384 * Clean variables using sanitize_text_field. Arrays are cleaned recursively.
385 * Non-scalar values are ignored.
386 *
387 * @param string|array $var Data to sanitize.
388 * @return string|array
389 */
390 function wc_clean( $var ) {
391 if ( is_array( $var ) ) {
392 return array_map( 'wc_clean', $var );
393 } else {
394 return is_scalar( $var ) ? sanitize_text_field( $var ) : $var;
395 }
396 }
397
398 /**
399 * Function wp_check_invalid_utf8 with recursive array support.
400 *
401 * @param string|array $var Data to sanitize.
402 * @return string|array
403 */
404 function wc_check_invalid_utf8( $var ) {
405 if ( is_array( $var ) ) {
406 return array_map( 'wc_check_invalid_utf8', $var );
407 } else {
408 return wp_check_invalid_utf8( $var );
409 }
410 }
411
412 /**
413 * Run wc_clean over posted textarea but maintain line breaks.
414 *
415 * @since 3.0.0
416 * @param string $var Data to sanitize.
417 * @return string
418 */
419 function wc_sanitize_textarea( $var ) {
420 return implode( "\n", array_map( 'wc_clean', explode( "\n", $var ) ) );
421 }
422
423 /**
424 * Sanitize a string destined to be a tooltip.
425 *
426 * @since 2.3.10 Tooltips are encoded with htmlspecialchars to prevent XSS. Should not be used in conjunction with esc_attr()
427 * @param string $var Data to sanitize.
428 * @return string
429 */
430 function wc_sanitize_tooltip( $var ) {
431 return htmlspecialchars(
432 wp_kses(
433 html_entity_decode( $var ),
434 array(
435 'br' => array(),
436 'em' => array(),
437 'strong' => array(),
438 'small' => array(),
439 'span' => array(),
440 'ul' => array(),
441 'li' => array(),
442 'ol' => array(),
443 'p' => array(),
444 )
445 )
446 );
447 }
448
449 /**
450 * Merge two arrays.
451 *
452 * @param array $a1 First array to merge.
453 * @param array $a2 Second array to merge.
454 * @return array
455 */
456 function wc_array_overlay( $a1, $a2 ) {
457 foreach ( $a1 as $k => $v ) {
458 if ( ! array_key_exists( $k, $a2 ) ) {
459 continue;
460 }
461 if ( is_array( $v ) && is_array( $a2[ $k ] ) ) {
462 $a1[ $k ] = wc_array_overlay( $v, $a2[ $k ] );
463 } else {
464 $a1[ $k ] = $a2[ $k ];
465 }
466 }
467 return $a1;
468 }
469
470 /**
471 * Formats a stock amount by running it through a filter.
472 *
473 * @param int|float $amount Stock amount.
474 * @return int|float
475 */
476 function wc_stock_amount( $amount ) {
477 return apply_filters( 'woocommerce_stock_amount', $amount );
478 }
479
480 /**
481 * Get the price format depending on the currency position.
482 *
483 * @return string
484 */
485 function get_woocommerce_price_format() {
486 $currency_pos = get_option( 'woocommerce_currency_pos' );
487 $format = '%1$s%2$s';
488
489 switch ( $currency_pos ) {
490 case 'left':
491 $format = '%1$s%2$s';
492 break;
493 case 'right':
494 $format = '%2$s%1$s';
495 break;
496 case 'left_space':
497 $format = '%1$s&nbsp;%2$s';
498 break;
499 case 'right_space':
500 $format = '%2$s&nbsp;%1$s';
501 break;
502 }
503
504 return apply_filters( 'woocommerce_price_format', $format, $currency_pos );
505 }
506
507 /**
508 * Return the thousand separator for prices.
509 *
510 * @since 2.3
511 * @return string
512 */
513 function wc_get_price_thousand_separator() {
514 return stripslashes( apply_filters( 'wc_get_price_thousand_separator', get_option( 'woocommerce_price_thousand_sep' ) ) );
515 }
516
517 /**
518 * Return the decimal separator for prices.
519 *
520 * @since 2.3
521 * @return string
522 */
523 function wc_get_price_decimal_separator() {
524 $separator = apply_filters( 'wc_get_price_decimal_separator', get_option( 'woocommerce_price_decimal_sep' ) );
525 return $separator ? stripslashes( $separator ) : '.';
526 }
527
528 /**
529 * Return the number of decimals after the decimal point.
530 *
531 * @since 2.3
532 * @return int
533 */
534 function wc_get_price_decimals() {
535 return absint( apply_filters( 'wc_get_price_decimals', get_option( 'woocommerce_price_num_decimals', 2 ) ) );
536 }
537
538 /**
539 * Format the price with a currency symbol.
540 *
541 * @param float $price Raw price.
542 * @param array $args Arguments to format a price {
543 * Array of arguments.
544 * Defaults to empty array.
545 *
546 * @type bool $ex_tax_label Adds exclude tax label.
547 * Defaults to false.
548 * @type string $currency Currency code.
549 * Defaults to empty string (Use the result from get_woocommerce_currency()).
550 * @type string $decimal_separator Decimal separator.
551 * Defaults the result of wc_get_price_decimal_separator().
552 * @type string $thousand_separator Thousand separator.
553 * Defaults the result of wc_get_price_thousand_separator().
554 * @type string $decimals Number of decimals.
555 * Defaults the result of wc_get_price_decimals().
556 * @type string $price_format Price format depending on the currency position.
557 * Defaults the result of get_woocommerce_price_format().
558 * }
559 * @return string
560 */
561 function wc_price( $price, $args = array() ) {
562 $args = apply_filters(
563 'wc_price_args',
564 wp_parse_args(
565 $args,
566 array(
567 'ex_tax_label' => false,
568 'currency' => '',
569 'decimal_separator' => wc_get_price_decimal_separator(),
570 'thousand_separator' => wc_get_price_thousand_separator(),
571 'decimals' => wc_get_price_decimals(),
572 'price_format' => get_woocommerce_price_format(),
573 )
574 )
575 );
576
577 $original_price = $price;
578
579 // Convert to float to avoid issues on PHP 8.
580 $price = (float) $price;
581
582 $unformatted_price = $price;
583 $negative = $price < 0;
584
585 /**
586 * Filter raw price.
587 *
588 * @param float $raw_price Raw price.
589 * @param float|string $original_price Original price as float, or empty string. Since 5.0.0.
590 */
591 $price = apply_filters( 'raw_woocommerce_price', $negative ? $price * -1 : $price, $original_price );
592
593 /**
594 * Filter formatted price.
595 *
596 * @param float $formatted_price Formatted price.
597 * @param float $price Unformatted price.
598 * @param int $decimals Number of decimals.
599 * @param string $decimal_separator Decimal separator.
600 * @param string $thousand_separator Thousand separator.
601 * @param float|string $original_price Original price as float, or empty string. Since 5.0.0.
602 */
603 $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 );
604
605 if ( apply_filters( 'woocommerce_price_trim_zeros', false ) && $args['decimals'] > 0 ) {
606 $price = wc_trim_zeros( $price );
607 }
608
609 $formatted_price = ( $negative ? '-' : '' ) . sprintf( $args['price_format'], '<span class="woocommerce-Price-currencySymbol">' . get_woocommerce_currency_symbol( $args['currency'] ) . '</span>', $price );
610 $return = '<span class="woocommerce-Price-amount amount"><bdi>' . $formatted_price . '</bdi></span>';
611
612 if ( $args['ex_tax_label'] && wc_tax_enabled() ) {
613 $return .= ' <small class="woocommerce-Price-taxLabel tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
614 }
615
616 /**
617 * Filters the string of price markup.
618 *
619 * @param string $return Price HTML markup.
620 * @param string $price Formatted price.
621 * @param array $args Pass on the args.
622 * @param float $unformatted_price Price as float to allow plugins custom formatting. Since 3.2.0.
623 * @param float|string $original_price Original price as float, or empty string. Since 5.0.0.
624 */
625 return apply_filters( 'wc_price', $return, $price, $args, $unformatted_price, $original_price );
626 }
627
628 /**
629 * Notation to numbers.
630 *
631 * This function transforms the php.ini notation for numbers (like '2M') to an integer.
632 *
633 * @param string $size Size value.
634 * @return int
635 */
636 function wc_let_to_num( $size ) {
637 $l = substr( $size, -1 );
638 $ret = (int) substr( $size, 0, -1 );
639 switch ( strtoupper( $l ) ) {
640 case 'P':
641 $ret *= 1024;
642 // No break.
643 case 'T':
644 $ret *= 1024;
645 // No break.
646 case 'G':
647 $ret *= 1024;
648 // No break.
649 case 'M':
650 $ret *= 1024;
651 // No break.
652 case 'K':
653 $ret *= 1024;
654 // No break.
655 }
656 return $ret;
657 }
658
659 /**
660 * WooCommerce Date Format - Allows to change date format for everything WooCommerce.
661 *
662 * @return string
663 */
664 function wc_date_format() {
665 $date_format = get_option( 'date_format' );
666 if ( empty( $date_format ) ) {
667 // Return default date format if the option is empty.
668 $date_format = 'F j, Y';
669 }
670 return apply_filters( 'woocommerce_date_format', $date_format );
671 }
672
673 /**
674 * WooCommerce Time Format - Allows to change time format for everything WooCommerce.
675 *
676 * @return string
677 */
678 function wc_time_format() {
679 $time_format = get_option( 'time_format' );
680 if ( empty( $time_format ) ) {
681 // Return default time format if the option is empty.
682 $time_format = 'g:i a';
683 }
684 return apply_filters( 'woocommerce_time_format', $time_format );
685 }
686
687 /**
688 * Convert mysql datetime to PHP timestamp, forcing UTC. Wrapper for strtotime.
689 *
690 * Based on wcs_strtotime_dark_knight() from WC Subscriptions by Prospress.
691 *
692 * @since 3.0.0
693 * @param string $time_string Time string.
694 * @param int|null $from_timestamp Timestamp to convert from.
695 * @return int
696 */
697 function wc_string_to_timestamp( $time_string, $from_timestamp = null ) {
698 $original_timezone = date_default_timezone_get();
699
700 // @codingStandardsIgnoreStart
701 date_default_timezone_set( 'UTC' );
702
703 if ( null === $from_timestamp ) {
704 $next_timestamp = strtotime( $time_string );
705 } else {
706 $next_timestamp = strtotime( $time_string, $from_timestamp );
707 }
708
709 date_default_timezone_set( $original_timezone );
710 // @codingStandardsIgnoreEnd
711
712 return $next_timestamp;
713 }
714
715 /**
716 * Convert a date string to a WC_DateTime.
717 *
718 * @since 3.1.0
719 * @param string $time_string Time string.
720 * @return WC_DateTime
721 */
722 function wc_string_to_datetime( $time_string ) {
723 // Strings are defined in local WP timezone. Convert to UTC.
724 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 ) ) {
725 $offset = ! empty( $date_bits[7] ) ? iso8601_timezone_to_offset( $date_bits[7] ) : wc_timezone_offset();
726 $timestamp = gmmktime( $date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1] ) - $offset;
727 } else {
728 $timestamp = wc_string_to_timestamp( get_gmt_from_date( gmdate( 'Y-m-d H:i:s', wc_string_to_timestamp( $time_string ) ) ) );
729 }
730 $datetime = new WC_DateTime( "@{$timestamp}", new DateTimeZone( 'UTC' ) );
731
732 // Set local timezone or offset.
733 if ( get_option( 'timezone_string' ) ) {
734 $datetime->setTimezone( new DateTimeZone( wc_timezone_string() ) );
735 } else {
736 $datetime->set_utc_offset( wc_timezone_offset() );
737 }
738
739 return $datetime;
740 }
741
742 /**
743 * WooCommerce Timezone - helper to retrieve the timezone string for a site until.
744 * a WP core method exists (see https://core.trac.wordpress.org/ticket/24730).
745 *
746 * Adapted from https://secure.php.net/manual/en/function.timezone-name-from-abbr.php#89155.
747 *
748 * @since 2.1
749 * @return string PHP timezone string for the site
750 */
751 function wc_timezone_string() {
752 // Added in WordPress 5.3 Ref https://developer.wordpress.org/reference/functions/wp_timezone_string/.
753 if ( function_exists( 'wp_timezone_string' ) ) {
754 return wp_timezone_string();
755 }
756
757 // If site timezone string exists, return it.
758 $timezone = get_option( 'timezone_string' );
759 if ( $timezone ) {
760 return $timezone;
761 }
762
763 // Get UTC offset, if it isn't set then return UTC.
764 $utc_offset = floatval( get_option( 'gmt_offset', 0 ) );
765 if ( ! is_numeric( $utc_offset ) || 0.0 === $utc_offset ) {
766 return 'UTC';
767 }
768
769 // Adjust UTC offset from hours to seconds.
770 $utc_offset = (int) ( $utc_offset * 3600 );
771
772 // Attempt to guess the timezone string from the UTC offset.
773 $timezone = timezone_name_from_abbr( '', $utc_offset );
774 if ( $timezone ) {
775 return $timezone;
776 }
777
778 // Last try, guess timezone string manually.
779 foreach ( timezone_abbreviations_list() as $abbr ) {
780 foreach ( $abbr as $city ) {
781 // 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.
782 if ( (bool) date( 'I' ) === (bool) $city['dst'] && $city['timezone_id'] && intval( $city['offset'] ) === $utc_offset ) { // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
783 return $city['timezone_id'];
784 }
785 }
786 }
787
788 // Fallback to UTC.
789 return 'UTC';
790 }
791
792 /**
793 * Get timezone offset in seconds.
794 *
795 * @since 3.0.0
796 * @return float
797 */
798 function wc_timezone_offset() {
799 $timezone = get_option( 'timezone_string' );
800
801 if ( $timezone ) {
802 $timezone_object = new DateTimeZone( $timezone );
803 return $timezone_object->getOffset( new DateTime( 'now' ) );
804 } else {
805 return floatval( get_option( 'gmt_offset', 0 ) ) * HOUR_IN_SECONDS;
806 }
807 }
808
809 /**
810 * Callback which can flatten post meta (gets the first value if it's an array).
811 *
812 * @since 3.0.0
813 * @param array $value Value to flatten.
814 * @return mixed
815 */
816 function wc_flatten_meta_callback( $value ) {
817 return is_array( $value ) ? current( $value ) : $value;
818 }
819
820 if ( ! function_exists( 'wc_rgb_from_hex' ) ) {
821
822 /**
823 * Convert RGB to HEX.
824 *
825 * @param mixed $color Color.
826 *
827 * @return array
828 */
829 function wc_rgb_from_hex( $color ) {
830 $color = str_replace( '#', '', $color );
831 // Convert shorthand colors to full format, e.g. "FFF" -> "FFFFFF".
832 $color = preg_replace( '~^(.)(.)(.)$~', '$1$1$2$2$3$3', $color );
833
834 $rgb = array();
835 $rgb['R'] = hexdec( $color[0] . $color[1] );
836 $rgb['G'] = hexdec( $color[2] . $color[3] );
837 $rgb['B'] = hexdec( $color[4] . $color[5] );
838
839 return $rgb;
840 }
841 }
842
843 if ( ! function_exists( 'wc_hex_darker' ) ) {
844
845 /**
846 * Make HEX color darker.
847 *
848 * @param mixed $color Color.
849 * @param int $factor Darker factor.
850 * Defaults to 30.
851 * @return string
852 */
853 function wc_hex_darker( $color, $factor = 30 ) {
854 $base = wc_rgb_from_hex( $color );
855 $color = '#';
856
857 foreach ( $base as $k => $v ) {
858 $amount = $v / 100;
859 $amount = NumberUtil::round( $amount * $factor );
860 $new_decimal = $v - $amount;
861
862 $new_hex_component = dechex( $new_decimal );
863 if ( strlen( $new_hex_component ) < 2 ) {
864 $new_hex_component = '0' . $new_hex_component;
865 }
866 $color .= $new_hex_component;
867 }
868
869 return $color;
870 }
871 }
872
873 if ( ! function_exists( 'wc_hex_lighter' ) ) {
874
875 /**
876 * Make HEX color lighter.
877 *
878 * @param mixed $color Color.
879 * @param int $factor Lighter factor.
880 * Defaults to 30.
881 * @return string
882 */
883 function wc_hex_lighter( $color, $factor = 30 ) {
884 $base = wc_rgb_from_hex( $color );
885 $color = '#';
886
887 foreach ( $base as $k => $v ) {
888 $amount = 255 - $v;
889 $amount = $amount / 100;
890 $amount = NumberUtil::round( $amount * $factor );
891 $new_decimal = $v + $amount;
892
893 $new_hex_component = dechex( $new_decimal );
894 if ( strlen( $new_hex_component ) < 2 ) {
895 $new_hex_component = '0' . $new_hex_component;
896 }
897 $color .= $new_hex_component;
898 }
899
900 return $color;
901 }
902 }
903
904 if ( ! function_exists( 'wc_hex_is_light' ) ) {
905
906 /**
907 * Determine whether a hex color is light.
908 *
909 * @param mixed $color Color.
910 * @return bool True if a light color.
911 */
912 function wc_hex_is_light( $color ) {
913 $hex = str_replace( '#', '', $color );
914
915 $c_r = hexdec( substr( $hex, 0, 2 ) );
916 $c_g = hexdec( substr( $hex, 2, 2 ) );
917 $c_b = hexdec( substr( $hex, 4, 2 ) );
918
919 $brightness = ( ( $c_r * 299 ) + ( $c_g * 587 ) + ( $c_b * 114 ) ) / 1000;
920
921 return $brightness > 155;
922 }
923 }
924
925 if ( ! function_exists( 'wc_light_or_dark' ) ) {
926
927 /**
928 * Detect if we should use a light or dark color on a background color.
929 *
930 * @param mixed $color Color.
931 * @param string $dark Darkest reference.
932 * Defaults to '#000000'.
933 * @param string $light Lightest reference.
934 * Defaults to '#FFFFFF'.
935 * @return string
936 */
937 function wc_light_or_dark( $color, $dark = '#000000', $light = '#FFFFFF' ) {
938 return wc_hex_is_light( $color ) ? $dark : $light;
939 }
940 }
941
942 if ( ! function_exists( 'wc_format_hex' ) ) {
943
944 /**
945 * Format string as hex.
946 *
947 * @param string $hex HEX color.
948 * @return string|null
949 */
950 function wc_format_hex( $hex ) {
951 $hex = trim( str_replace( '#', '', $hex ) );
952
953 if ( strlen( $hex ) === 3 ) {
954 $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
955 }
956
957 return $hex ? '#' . $hex : null;
958 }
959 }
960
961 /**
962 * Format the postcode according to the country and length of the postcode.
963 *
964 * @param string $postcode Unformatted postcode.
965 * @param string $country Base country.
966 * @return string
967 */
968 function wc_format_postcode( $postcode, $country ) {
969 $postcode = wc_normalize_postcode( $postcode );
970
971 switch ( $country ) {
972 case 'CA':
973 case 'GB':
974 $postcode = substr_replace( $postcode, ' ', -3, 0 );
975 break;
976 case 'IE':
977 $postcode = substr_replace( $postcode, ' ', 3, 0 );
978 break;
979 case 'BR':
980 case 'PL':
981 $postcode = substr_replace( $postcode, '-', -3, 0 );
982 break;
983 case 'JP':
984 $postcode = substr_replace( $postcode, '-', 3, 0 );
985 break;
986 case 'PT':
987 $postcode = substr_replace( $postcode, '-', 4, 0 );
988 break;
989 case 'PR':
990 case 'US':
991 $postcode = rtrim( substr_replace( $postcode, '-', 5, 0 ), '-' );
992 break;
993 case 'NL':
994 $postcode = substr_replace( $postcode, ' ', 4, 0 );
995 break;
996 }
997
998 return apply_filters( 'woocommerce_format_postcode', trim( $postcode ), $country );
999 }
1000
1001 /**
1002 * Normalize postcodes.
1003 *
1004 * Remove spaces and convert characters to uppercase.
1005 *
1006 * @since 2.6.0
1007 * @param string $postcode Postcode.
1008 * @return string
1009 */
1010 function wc_normalize_postcode( $postcode ) {
1011 return preg_replace( '/[\s\-]/', '', trim( wc_strtoupper( $postcode ) ) );
1012 }
1013
1014 /**
1015 * Format phone numbers.
1016 *
1017 * @param string $phone Phone number.
1018 * @return string
1019 */
1020 function wc_format_phone_number( $phone ) {
1021 if ( ! WC_Validation::is_phone( $phone ) ) {
1022 return '';
1023 }
1024 return preg_replace( '/[^0-9\+\-\(\)\s]/', '-', preg_replace( '/[\x00-\x1F\x7F-\xFF]/', '', $phone ) );
1025 }
1026
1027 /**
1028 * Sanitize phone number.
1029 * Allows only numbers and "+" (plus sign).
1030 *
1031 * @since 3.6.0
1032 * @param string $phone Phone number.
1033 * @return string
1034 */
1035 function wc_sanitize_phone_number( $phone ) {
1036 return preg_replace( '/[^\d+]/', '', $phone );
1037 }
1038
1039 /**
1040 * Wrapper for mb_strtoupper which see's if supported first.
1041 *
1042 * @since 3.1.0
1043 * @param string $string String to format.
1044 * @return string
1045 */
1046 function wc_strtoupper( $string ) {
1047 return function_exists( 'mb_strtoupper' ) ? mb_strtoupper( $string ) : strtoupper( $string );
1048 }
1049
1050 /**
1051 * Make a string lowercase.
1052 * Try to use mb_strtolower() when available.
1053 *
1054 * @since 2.3
1055 * @param string $string String to format.
1056 * @return string
1057 */
1058 function wc_strtolower( $string ) {
1059 return function_exists( 'mb_strtolower' ) ? mb_strtolower( $string ) : strtolower( $string );
1060 }
1061
1062 /**
1063 * Trim a string and append a suffix.
1064 *
1065 * @param string $string String to trim.
1066 * @param integer $chars Amount of characters.
1067 * Defaults to 200.
1068 * @param string $suffix Suffix.
1069 * Defaults to '...'.
1070 * @return string
1071 */
1072 function wc_trim_string( $string, $chars = 200, $suffix = '...' ) {
1073 if ( strlen( $string ) > $chars ) {
1074 if ( function_exists( 'mb_substr' ) ) {
1075 $string = mb_substr( $string, 0, ( $chars - mb_strlen( $suffix ) ) ) . $suffix;
1076 } else {
1077 $string = substr( $string, 0, ( $chars - strlen( $suffix ) ) ) . $suffix;
1078 }
1079 }
1080 return $string;
1081 }
1082
1083 /**
1084 * Format content to display shortcodes.
1085 *
1086 * @since 2.3.0
1087 * @param string $raw_string Raw string.
1088 * @return string
1089 */
1090 function wc_format_content( $raw_string ) {
1091 return apply_filters( 'woocommerce_format_content', apply_filters( 'woocommerce_short_description', $raw_string ), $raw_string );
1092 }
1093
1094 /**
1095 * Format product short description.
1096 * Adds support for Jetpack Markdown.
1097 *
1098 * @codeCoverageIgnore
1099 * @since 2.4.0
1100 * @param string $content Product short description.
1101 * @return string
1102 */
1103 function wc_format_product_short_description( $content ) {
1104 // Add support for Jetpack Markdown.
1105 if ( class_exists( 'WPCom_Markdown' ) ) {
1106 $markdown = WPCom_Markdown::get_instance();
1107
1108 return wpautop(
1109 $markdown->transform(
1110 $content,
1111 array(
1112 'unslash' => false,
1113 )
1114 )
1115 );
1116 }
1117
1118 return $content;
1119 }
1120
1121 /**
1122 * Formats curency symbols when saved in settings.
1123 *
1124 * @codeCoverageIgnore
1125 * @param string $value Option value.
1126 * @param array $option Option name.
1127 * @param string $raw_value Raw value.
1128 * @return string
1129 */
1130 function wc_format_option_price_separators( $value, $option, $raw_value ) {
1131 return wp_kses_post( $raw_value );
1132 }
1133 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_price_decimal_sep', 'wc_format_option_price_separators', 10, 3 );
1134 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_price_thousand_sep', 'wc_format_option_price_separators', 10, 3 );
1135
1136 /**
1137 * Formats decimals when saved in settings.
1138 *
1139 * @codeCoverageIgnore
1140 * @param string $value Option value.
1141 * @param array $option Option name.
1142 * @param string $raw_value Raw value.
1143 * @return string
1144 */
1145 function wc_format_option_price_num_decimals( $value, $option, $raw_value ) {
1146 return is_null( $raw_value ) ? 2 : absint( $raw_value );
1147 }
1148 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_price_num_decimals', 'wc_format_option_price_num_decimals', 10, 3 );
1149
1150 /**
1151 * Formats hold stock option and sets cron event up.
1152 *
1153 * @codeCoverageIgnore
1154 * @param string $value Option value.
1155 * @param array $option Option name.
1156 * @param string $raw_value Raw value.
1157 * @return string
1158 */
1159 function wc_format_option_hold_stock_minutes( $value, $option, $raw_value ) {
1160 $value = ! empty( $raw_value ) ? absint( $raw_value ) : ''; // Allow > 0 or set to ''.
1161
1162 wp_clear_scheduled_hook( 'woocommerce_cancel_unpaid_orders' );
1163
1164 if ( '' !== $value ) {
1165 $cancel_unpaid_interval = apply_filters( 'woocommerce_cancel_unpaid_orders_interval_minutes', absint( $value ) );
1166 wp_schedule_single_event( time() + ( absint( $cancel_unpaid_interval ) * 60 ), 'woocommerce_cancel_unpaid_orders' );
1167 }
1168
1169 return $value;
1170 }
1171 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_hold_stock_minutes', 'wc_format_option_hold_stock_minutes', 10, 3 );
1172
1173 /**
1174 * Sanitize terms from an attribute text based.
1175 *
1176 * @since 2.4.5
1177 * @param string $term Term value.
1178 * @return string
1179 */
1180 function wc_sanitize_term_text_based( $term ) {
1181 return trim( wp_strip_all_tags( wp_unslash( $term ) ) );
1182 }
1183
1184 if ( ! function_exists( 'wc_make_numeric_postcode' ) ) {
1185 /**
1186 * Make numeric postcode.
1187 *
1188 * Converts letters to numbers so we can do a simple range check on postcodes.
1189 * E.g. PE30 becomes 16050300 (P = 16, E = 05, 3 = 03, 0 = 00)
1190 *
1191 * @since 2.6.0
1192 * @param string $postcode Regular postcode.
1193 * @return string
1194 */
1195 function wc_make_numeric_postcode( $postcode ) {
1196 $postcode = str_replace( array( ' ', '-' ), '', $postcode );
1197 $postcode_length = strlen( $postcode );
1198 $letters_to_numbers = array_merge( array( 0 ), range( 'A', 'Z' ) );
1199 $letters_to_numbers = array_flip( $letters_to_numbers );
1200 $numeric_postcode = '';
1201
1202 for ( $i = 0; $i < $postcode_length; $i ++ ) {
1203 if ( is_numeric( $postcode[ $i ] ) ) {
1204 $numeric_postcode .= str_pad( $postcode[ $i ], 2, '0', STR_PAD_LEFT );
1205 } elseif ( isset( $letters_to_numbers[ $postcode[ $i ] ] ) ) {
1206 $numeric_postcode .= str_pad( $letters_to_numbers[ $postcode[ $i ] ], 2, '0', STR_PAD_LEFT );
1207 } else {
1208 $numeric_postcode .= '00';
1209 }
1210 }
1211
1212 return $numeric_postcode;
1213 }
1214 }
1215
1216 /**
1217 * Format the stock amount ready for display based on settings.
1218 *
1219 * @since 3.0.0
1220 * @param WC_Product $product Product object for which the stock you need to format.
1221 * @return string
1222 */
1223 function wc_format_stock_for_display( $product ) {
1224 $display = __( 'In stock', 'woocommerce' );
1225 $stock_amount = $product->get_stock_quantity();
1226
1227 switch ( get_option( 'woocommerce_stock_format' ) ) {
1228 case 'low_amount':
1229 if ( $stock_amount <= wc_get_low_stock_amount( $product ) ) {
1230 /* translators: %s: stock amount */
1231 $display = sprintf( __( 'Only %s left in stock', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
1232 }
1233 break;
1234 case '':
1235 /* translators: %s: stock amount */
1236 $display = sprintf( __( '%s in stock', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
1237 break;
1238 }
1239
1240 if ( $product->backorders_allowed() && $product->backorders_require_notification() ) {
1241 $display .= ' ' . __( '(can be backordered)', 'woocommerce' );
1242 }
1243
1244 return $display;
1245 }
1246
1247 /**
1248 * Format the stock quantity ready for display.
1249 *
1250 * @since 3.0.0
1251 * @param int $stock_quantity Stock quantity.
1252 * @param WC_Product $product Product instance so that we can pass through the filters.
1253 * @return string
1254 */
1255 function wc_format_stock_quantity_for_display( $stock_quantity, $product ) {
1256 return apply_filters( 'woocommerce_format_stock_quantity', $stock_quantity, $product );
1257 }
1258
1259 /**
1260 * Format a sale price for display.
1261 *
1262 * @since 3.0.0
1263 * @param string $regular_price Regular price.
1264 * @param string $sale_price Sale price.
1265 * @return string
1266 */
1267 function wc_format_sale_price( $regular_price, $sale_price ) {
1268 $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>';
1269 return apply_filters( 'woocommerce_format_sale_price', $price, $regular_price, $sale_price );
1270 }
1271
1272 /**
1273 * Format a price range for display.
1274 *
1275 * @param string $from Price from.
1276 * @param string $to Price to.
1277 * @return string
1278 */
1279 function wc_format_price_range( $from, $to ) {
1280 /* translators: 1: price from 2: price to */
1281 $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 );
1282 return apply_filters( 'woocommerce_format_price_range', $price, $from, $to );
1283 }
1284
1285 /**
1286 * Format a weight for display.
1287 *
1288 * @since 3.0.0
1289 * @param float $weight Weight.
1290 * @return string
1291 */
1292 function wc_format_weight( $weight ) {
1293 $weight_string = wc_format_localized_decimal( $weight );
1294
1295 if ( ! empty( $weight_string ) ) {
1296 $weight_string .= ' ' . get_option( 'woocommerce_weight_unit' );
1297 } else {
1298 $weight_string = __( 'N/A', 'woocommerce' );
1299 }
1300
1301 return apply_filters( 'woocommerce_format_weight', $weight_string, $weight );
1302 }
1303
1304 /**
1305 * Format dimensions for display.
1306 *
1307 * @since 3.0.0
1308 * @param array $dimensions Array of dimensions.
1309 * @return string
1310 */
1311 function wc_format_dimensions( $dimensions ) {
1312 $dimension_string = implode( ' &times; ', array_filter( array_map( 'wc_format_localized_decimal', $dimensions ) ) );
1313
1314 if ( ! empty( $dimension_string ) ) {
1315 $dimension_string .= ' ' . get_option( 'woocommerce_dimension_unit' );
1316 } else {
1317 $dimension_string = __( 'N/A', 'woocommerce' );
1318 }
1319
1320 return apply_filters( 'woocommerce_format_dimensions', $dimension_string, $dimensions );
1321 }
1322
1323 /**
1324 * Format a date for output.
1325 *
1326 * @since 3.0.0
1327 * @param WC_DateTime $date Instance of WC_DateTime.
1328 * @param string $format Data format.
1329 * Defaults to the wc_date_format function if not set.
1330 * @return string
1331 */
1332 function wc_format_datetime( $date, $format = '' ) {
1333 if ( ! $format ) {
1334 $format = wc_date_format();
1335 }
1336 if ( ! is_a( $date, 'WC_DateTime' ) ) {
1337 return '';
1338 }
1339 return $date->date_i18n( $format );
1340 }
1341
1342 /**
1343 * Process oEmbeds.
1344 *
1345 * @since 3.1.0
1346 * @param string $content Content.
1347 * @return string
1348 */
1349 function wc_do_oembeds( $content ) {
1350 global $wp_embed;
1351
1352 $content = $wp_embed->autoembed( $content );
1353
1354 return $content;
1355 }
1356
1357 /**
1358 * Get part of a string before :.
1359 *
1360 * Used for example in shipping methods ids where they take the format
1361 * method_id:instance_id
1362 *
1363 * @since 3.2.0
1364 * @param string $string String to extract.
1365 * @return string
1366 */
1367 function wc_get_string_before_colon( $string ) {
1368 return trim( current( explode( ':', (string) $string ) ) );
1369 }
1370
1371 /**
1372 * Array merge and sum function.
1373 *
1374 * Source: https://gist.github.com/Nickology/f700e319cbafab5eaedc
1375 *
1376 * @since 3.2.0
1377 * @return array
1378 */
1379 function wc_array_merge_recursive_numeric() {
1380 $arrays = func_get_args();
1381
1382 // If there's only one array, it's already merged.
1383 if ( 1 === count( $arrays ) ) {
1384 return $arrays[0];
1385 }
1386
1387 // Remove any items in $arrays that are NOT arrays.
1388 foreach ( $arrays as $key => $array ) {
1389 if ( ! is_array( $array ) ) {
1390 unset( $arrays[ $key ] );
1391 }
1392 }
1393
1394 // We start by setting the first array as our final array.
1395 // We will merge all other arrays with this one.
1396 $final = array_shift( $arrays );
1397
1398 foreach ( $arrays as $b ) {
1399 foreach ( $final as $key => $value ) {
1400 // If $key does not exist in $b, then it is unique and can be safely merged.
1401 if ( ! isset( $b[ $key ] ) ) {
1402 $final[ $key ] = $value;
1403 } else {
1404 // If $key is present in $b, then we need to merge and sum numeric values in both.
1405 if ( is_numeric( $value ) && is_numeric( $b[ $key ] ) ) {
1406 // If both values for these keys are numeric, we sum them.
1407 $final[ $key ] = $value + $b[ $key ];
1408 } elseif ( is_array( $value ) && is_array( $b[ $key ] ) ) {
1409 // If both values are arrays, we recursively call ourself.
1410 $final[ $key ] = wc_array_merge_recursive_numeric( $value, $b[ $key ] );
1411 } else {
1412 // If both keys exist but differ in type, then we cannot merge them.
1413 // In this scenario, we will $b's value for $key is used.
1414 $final[ $key ] = $b[ $key ];
1415 }
1416 }
1417 }
1418
1419 // Finally, we need to merge any keys that exist only in $b.
1420 foreach ( $b as $key => $value ) {
1421 if ( ! isset( $final[ $key ] ) ) {
1422 $final[ $key ] = $value;
1423 }
1424 }
1425 }
1426
1427 return $final;
1428 }
1429
1430 /**
1431 * Implode and escape HTML attributes for output.
1432 *
1433 * @since 3.3.0
1434 * @param array $raw_attributes Attribute name value pairs.
1435 * @return string
1436 */
1437 function wc_implode_html_attributes( $raw_attributes ) {
1438 $attributes = array();
1439 foreach ( $raw_attributes as $name => $value ) {
1440 $attributes[] = esc_attr( $name ) . '="' . esc_attr( $value ) . '"';
1441 }
1442 return implode( ' ', $attributes );
1443 }
1444
1445 /**
1446 * Escape JSON for use on HTML or attribute text nodes.
1447 *
1448 * @since 3.5.5
1449 * @param string $json JSON to escape.
1450 * @param bool $html True if escaping for HTML text node, false for attributes. Determines how quotes are handled.
1451 * @return string Escaped JSON.
1452 */
1453 function wc_esc_json( $json, $html = false ) {
1454 return _wp_specialchars(
1455 $json,
1456 $html ? ENT_NOQUOTES : ENT_QUOTES, // Escape quotes in attribute nodes only.
1457 'UTF-8', // json_encode() outputs UTF-8 (really just ASCII), not the blog's charset.
1458 true // Double escape entities: `&amp;` -> `&amp;amp;`.
1459 );
1460 }
1461
1462 /**
1463 * Parse a relative date option from the settings API into a standard format.
1464 *
1465 * @since 3.4.0
1466 * @param mixed $raw_value Value stored in DB.
1467 * @return array Nicely formatted array with number and unit values.
1468 */
1469 function wc_parse_relative_date_option( $raw_value ) {
1470 $periods = array(
1471 'days' => __( 'Day(s)', 'woocommerce' ),
1472 'weeks' => __( 'Week(s)', 'woocommerce' ),
1473 'months' => __( 'Month(s)', 'woocommerce' ),
1474 'years' => __( 'Year(s)', 'woocommerce' ),
1475 );
1476
1477 $value = wp_parse_args(
1478 (array) $raw_value,
1479 array(
1480 'number' => '',
1481 'unit' => 'days',
1482 )
1483 );
1484
1485 $value['number'] = ! empty( $value['number'] ) ? absint( $value['number'] ) : '';
1486
1487 if ( ! in_array( $value['unit'], array_keys( $periods ), true ) ) {
1488 $value['unit'] = 'days';
1489 }
1490
1491 return $value;
1492 }
1493
1494 /**
1495 * Format the endpoint slug, strip out anything not allowed in a url.
1496 *
1497 * @since 3.5.0
1498 * @param string $raw_value The raw value.
1499 * @return string
1500 */
1501 function wc_sanitize_endpoint_slug( $raw_value ) {
1502 return sanitize_title( $raw_value );
1503 }
1504 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_checkout_pay_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1505 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_checkout_order_received_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1506 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_add_payment_method_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1507 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_delete_payment_method_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1508 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_set_default_payment_method_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1509 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_orders_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1510 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_view_order_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1511 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_downloads_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1512 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_edit_account_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1513 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_edit_address_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1514 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_payment_methods_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1515 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_myaccount_lost_password_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1516 add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_logout_endpoint', 'wc_sanitize_endpoint_slug', 10, 1 );
1517