Нет описания

wc-formatting-functions.php 43KB

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