wc-cart-functions.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. <?php
  2. /**
  3. * WooCommerce Cart Functions
  4. *
  5. * Functions for cart specific things.
  6. *
  7. * @package WooCommerce/Functions
  8. * @version 2.5.0
  9. */
  10. defined( 'ABSPATH' ) || exit;
  11. /**
  12. * Prevent password protected products being added to the cart.
  13. *
  14. * @param bool $passed Validation.
  15. * @param int $product_id Product ID.
  16. * @return bool
  17. */
  18. function wc_protected_product_add_to_cart( $passed, $product_id ) {
  19. if ( post_password_required( $product_id ) ) {
  20. $passed = false;
  21. wc_add_notice( __( 'This product is protected and cannot be purchased.', 'woocommerce' ), 'error' );
  22. }
  23. return $passed;
  24. }
  25. add_filter( 'woocommerce_add_to_cart_validation', 'wc_protected_product_add_to_cart', 10, 2 );
  26. /**
  27. * Clears the cart session when called.
  28. */
  29. function wc_empty_cart() {
  30. if ( ! isset( WC()->cart ) || '' === WC()->cart ) {
  31. WC()->cart = new WC_Cart();
  32. }
  33. WC()->cart->empty_cart( false );
  34. }
  35. /**
  36. * Load the persistent cart.
  37. *
  38. * @param string $user_login User login.
  39. * @param WP_User $user User data.
  40. * @deprecated 2.3
  41. */
  42. function wc_load_persistent_cart( $user_login, $user ) {
  43. if ( ! $user || ! apply_filters( 'woocommerce_persistent_cart_enabled', true ) ) {
  44. return;
  45. }
  46. $saved_cart = get_user_meta( $user->ID, '_woocommerce_persistent_cart_' . get_current_blog_id(), true );
  47. if ( ! $saved_cart ) {
  48. return;
  49. }
  50. $cart = WC()->session->cart;
  51. if ( empty( $cart ) || ! is_array( $cart ) || 0 === count( $cart ) ) {
  52. WC()->session->cart = $saved_cart['cart'];
  53. }
  54. }
  55. /**
  56. * Retrieves unvalidated referer from '_wp_http_referer' or HTTP referer.
  57. *
  58. * Do not use for redirects, use {@see wp_get_referer()} instead.
  59. *
  60. * @since 2.6.1
  61. * @return string|false Referer URL on success, false on failure.
  62. */
  63. function wc_get_raw_referer() {
  64. if ( function_exists( 'wp_get_raw_referer' ) ) {
  65. return wp_get_raw_referer();
  66. }
  67. if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) { // WPCS: input var ok, CSRF ok.
  68. return wp_unslash( $_REQUEST['_wp_http_referer'] ); // WPCS: input var ok, CSRF ok, sanitization ok.
  69. } elseif ( ! empty( $_SERVER['HTTP_REFERER'] ) ) { // WPCS: input var ok, CSRF ok.
  70. return wp_unslash( $_SERVER['HTTP_REFERER'] ); // WPCS: input var ok, CSRF ok, sanitization ok.
  71. }
  72. return false;
  73. }
  74. /**
  75. * Add to cart messages.
  76. *
  77. * @param int|array $products Product ID list or single product ID.
  78. * @param bool $show_qty Should qty's be shown? Added in 2.6.0.
  79. * @param bool $return Return message rather than add it.
  80. *
  81. * @return mixed
  82. */
  83. function wc_add_to_cart_message( $products, $show_qty = false, $return = false ) {
  84. $titles = array();
  85. $count = 0;
  86. if ( ! is_array( $products ) ) {
  87. $products = array( $products => 1 );
  88. $show_qty = false;
  89. }
  90. if ( ! $show_qty ) {
  91. $products = array_fill_keys( array_keys( $products ), 1 );
  92. }
  93. foreach ( $products as $product_id => $qty ) {
  94. /* translators: %s: product name */
  95. $titles[] = ( $qty > 1 ? absint( $qty ) . ' &times; ' : '' ) . sprintf( _x( '&ldquo;%s&rdquo;', 'Item name in quotes', 'woocommerce' ), strip_tags( get_the_title( $product_id ) ) );
  96. $count += $qty;
  97. }
  98. $titles = array_filter( $titles );
  99. /* translators: %s: product name */
  100. $added_text = sprintf( _n( '%s has been added to your cart.', '%s have been added to your cart.', $count, 'woocommerce' ), wc_format_list_of_items( $titles ) );
  101. // Output success messages.
  102. if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
  103. $return_to = apply_filters( 'woocommerce_continue_shopping_redirect', wc_get_raw_referer() ? wp_validate_redirect( wc_get_raw_referer(), false ) : wc_get_page_permalink( 'shop' ) );
  104. $message = sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', esc_url( $return_to ), esc_html__( 'Continue shopping', 'woocommerce' ), esc_html( $added_text ) );
  105. } else {
  106. $message = sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', esc_url( wc_get_page_permalink( 'cart' ) ), esc_html__( 'View cart', 'woocommerce' ), esc_html( $added_text ) );
  107. }
  108. if ( has_filter( 'wc_add_to_cart_message' ) ) {
  109. wc_deprecated_function( 'The wc_add_to_cart_message filter', '3.0', 'wc_add_to_cart_message_html' );
  110. $message = apply_filters( 'wc_add_to_cart_message', $message, $product_id );
  111. }
  112. $message = apply_filters( 'wc_add_to_cart_message_html', $message, $products );
  113. if ( $return ) {
  114. return $message;
  115. } else {
  116. wc_add_notice( $message );
  117. }
  118. }
  119. /**
  120. * Comma separate a list of item names, and replace final comma with 'and'.
  121. *
  122. * @param array $items Cart items.
  123. * @return string
  124. */
  125. function wc_format_list_of_items( $items ) {
  126. $item_string = '';
  127. foreach ( $items as $key => $item ) {
  128. $item_string .= $item;
  129. if ( count( $items ) === $key + 2 ) {
  130. $item_string .= ' ' . __( 'and', 'woocommerce' ) . ' ';
  131. } elseif ( count( $items ) !== $key + 1 ) {
  132. $item_string .= ', ';
  133. }
  134. }
  135. return $item_string;
  136. }
  137. /**
  138. * Clear cart after payment.
  139. */
  140. function wc_clear_cart_after_payment() {
  141. global $wp;
  142. if ( ! empty( $wp->query_vars['order-received'] ) ) {
  143. $order_id = absint( $wp->query_vars['order-received'] );
  144. $order_key = isset( $_GET['key'] ) ? wc_clean( wp_unslash( $_GET['key'] ) ) : ''; // WPCS: input var ok, CSRF ok.
  145. if ( $order_id > 0 ) {
  146. $order = wc_get_order( $order_id );
  147. if ( $order && $order->get_order_key() === $order_key ) {
  148. WC()->cart->empty_cart();
  149. }
  150. }
  151. }
  152. if ( WC()->session->order_awaiting_payment > 0 ) {
  153. $order = wc_get_order( WC()->session->order_awaiting_payment );
  154. if ( $order && $order->get_id() > 0 ) {
  155. // If the order has not failed, or is not pending, the order must have gone through.
  156. if ( ! $order->has_status( array( 'failed', 'pending', 'cancelled' ) ) ) {
  157. WC()->cart->empty_cart();
  158. }
  159. }
  160. }
  161. }
  162. add_action( 'get_header', 'wc_clear_cart_after_payment' );
  163. /**
  164. * Get the subtotal.
  165. */
  166. function wc_cart_totals_subtotal_html() {
  167. echo WC()->cart->get_cart_subtotal(); // WPCS: XSS ok.
  168. }
  169. /**
  170. * Get shipping methods.
  171. */
  172. function wc_cart_totals_shipping_html() {
  173. $packages = WC()->shipping->get_packages();
  174. $first = true;
  175. foreach ( $packages as $i => $package ) {
  176. $chosen_method = isset( WC()->session->chosen_shipping_methods[ $i ] ) ? WC()->session->chosen_shipping_methods[ $i ] : '';
  177. $product_names = array();
  178. if ( count( $packages ) > 1 ) {
  179. foreach ( $package['contents'] as $item_id => $values ) {
  180. $product_names[ $item_id ] = $values['data']->get_name() . ' &times;' . $values['quantity'];
  181. }
  182. $product_names = apply_filters( 'woocommerce_shipping_package_details_array', $product_names, $package );
  183. }
  184. wc_get_template(
  185. 'cart/cart-shipping.php', array(
  186. 'package' => $package,
  187. 'available_methods' => $package['rates'],
  188. 'show_package_details' => count( $packages ) > 1,
  189. 'show_shipping_calculator' => is_cart() && $first,
  190. 'package_details' => implode( ', ', $product_names ),
  191. /* translators: %d: shipping package number */
  192. 'package_name' => apply_filters( 'woocommerce_shipping_package_name', ( ( $i + 1 ) > 1 ) ? sprintf( _x( 'Shipping %d', 'shipping packages', 'woocommerce' ), ( $i + 1 ) ) : _x( 'Shipping', 'shipping packages', 'woocommerce' ), $i, $package ),
  193. 'index' => $i,
  194. 'chosen_method' => $chosen_method,
  195. )
  196. );
  197. $first = false;
  198. }
  199. }
  200. /**
  201. * Get taxes total.
  202. */
  203. function wc_cart_totals_taxes_total_html() {
  204. echo apply_filters( 'woocommerce_cart_totals_taxes_total_html', wc_price( WC()->cart->get_taxes_total() ) ); // WPCS: XSS ok.
  205. }
  206. /**
  207. * Get a coupon label.
  208. *
  209. * @param string|WC_Coupon $coupon Coupon data or code.
  210. * @param bool $echo Echo or return.
  211. *
  212. * @return string
  213. */
  214. function wc_cart_totals_coupon_label( $coupon, $echo = true ) {
  215. if ( is_string( $coupon ) ) {
  216. $coupon = new WC_Coupon( $coupon );
  217. }
  218. /* translators: %s: coupon code */
  219. $label = apply_filters( 'woocommerce_cart_totals_coupon_label', sprintf( esc_html__( 'Coupon: %s', 'woocommerce' ), $coupon->get_code() ), $coupon );
  220. if ( $echo ) {
  221. echo $label; // WPCS: XSS ok.
  222. } else {
  223. return $label;
  224. }
  225. }
  226. /**
  227. * Get coupon display HTML.
  228. *
  229. * @param string|WC_Coupon $coupon Coupon data or code.
  230. */
  231. function wc_cart_totals_coupon_html( $coupon ) {
  232. if ( is_string( $coupon ) ) {
  233. $coupon = new WC_Coupon( $coupon );
  234. }
  235. $discount_amount_html = '';
  236. $amount = WC()->cart->get_coupon_discount_amount( $coupon->get_code(), WC()->cart->display_cart_ex_tax );
  237. $discount_amount_html = '-' . wc_price( $amount );
  238. if ( $coupon->get_free_shipping() && empty( $amount ) ) {
  239. $discount_amount_html = __( 'Free shipping coupon', 'woocommerce' );
  240. }
  241. $discount_amount_html = apply_filters( 'woocommerce_coupon_discount_amount_html', $discount_amount_html, $coupon );
  242. $coupon_html = $discount_amount_html . ' <a href="' . esc_url( add_query_arg( 'remove_coupon', rawurlencode( $coupon->get_code() ), defined( 'WOOCOMMERCE_CHECKOUT' ) ? wc_get_checkout_url() : wc_get_cart_url() ) ) . '" class="woocommerce-remove-coupon" data-coupon="' . esc_attr( $coupon->get_code() ) . '">' . __( '[Remove]', 'woocommerce' ) . '</a>';
  243. echo wp_kses( apply_filters( 'woocommerce_cart_totals_coupon_html', $coupon_html, $coupon, $discount_amount_html ), array_replace_recursive( wp_kses_allowed_html( 'post' ), array( 'a' => array( 'data-coupon' => true ) ) ) ); // phpcs:ignore PHPCompatibility.PHP.NewFunctions.array_replace_recursiveFound
  244. }
  245. /**
  246. * Get order total html including inc tax if needed.
  247. */
  248. function wc_cart_totals_order_total_html() {
  249. $value = '<strong>' . WC()->cart->get_total() . '</strong> ';
  250. // If prices are tax inclusive, show taxes here.
  251. if ( wc_tax_enabled() && WC()->cart->display_prices_including_tax() ) {
  252. $tax_string_array = array();
  253. $cart_tax_totals = WC()->cart->get_tax_totals();
  254. if ( get_option( 'woocommerce_tax_total_display' ) === 'itemized' ) {
  255. foreach ( $cart_tax_totals as $code => $tax ) {
  256. $tax_string_array[] = sprintf( '%s %s', $tax->formatted_amount, $tax->label );
  257. }
  258. } elseif ( ! empty( $cart_tax_totals ) ) {
  259. $tax_string_array[] = sprintf( '%s %s', wc_price( WC()->cart->get_taxes_total( true, true ) ), WC()->countries->tax_or_vat() );
  260. }
  261. if ( ! empty( $tax_string_array ) ) {
  262. $taxable_address = WC()->customer->get_taxable_address();
  263. /* translators: %s: country name */
  264. $estimated_text = WC()->customer->is_customer_outside_base() && ! WC()->customer->has_calculated_shipping() ? sprintf( ' ' . __( 'estimated for %s', 'woocommerce' ), WC()->countries->estimated_for_prefix( $taxable_address[0] ) . WC()->countries->countries[ $taxable_address[0] ] ) : '';
  265. /* translators: %s: tax information */
  266. $value .= '<small class="includes_tax">' . sprintf( __( '(includes %s)', 'woocommerce' ), implode( ', ', $tax_string_array ) . $estimated_text ) . '</small>';
  267. }
  268. }
  269. echo apply_filters( 'woocommerce_cart_totals_order_total_html', $value ); // WPCS: XSS ok.
  270. }
  271. /**
  272. * Get the fee value.
  273. *
  274. * @param object $fee Fee data.
  275. */
  276. function wc_cart_totals_fee_html( $fee ) {
  277. $cart_totals_fee_html = WC()->cart->display_prices_including_tax() ? wc_price( $fee->total + $fee->tax ) : wc_price( $fee->total );
  278. echo apply_filters( 'woocommerce_cart_totals_fee_html', $cart_totals_fee_html, $fee ); // WPCS: XSS ok.
  279. }
  280. /**
  281. * Get a shipping methods full label including price.
  282. *
  283. * @param WC_Shipping_Rate $method Shipping method rate data.
  284. * @return string
  285. */
  286. function wc_cart_totals_shipping_method_label( $method ) {
  287. $label = $method->get_label();
  288. if ( $method->cost >= 0 && $method->get_method_id() !== 'free_shipping' ) {
  289. if ( WC()->cart->display_prices_including_tax() ) {
  290. $label .= ': ' . wc_price( $method->cost + $method->get_shipping_tax() );
  291. if ( $method->get_shipping_tax() > 0 && ! wc_prices_include_tax() ) {
  292. $label .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
  293. }
  294. } else {
  295. $label .= ': ' . wc_price( $method->cost );
  296. if ( $method->get_shipping_tax() > 0 && wc_prices_include_tax() ) {
  297. $label .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
  298. }
  299. }
  300. }
  301. return apply_filters( 'woocommerce_cart_shipping_method_full_label', $label, $method );
  302. }
  303. /**
  304. * Round discount.
  305. *
  306. * @param double $value Amount to round.
  307. * @param int $precision DP to round.
  308. * @return float
  309. */
  310. function wc_cart_round_discount( $value, $precision ) {
  311. return wc_round_discount( $value, $precision );
  312. }
  313. /**
  314. * Gets chosen shipping method IDs from chosen_shipping_methods session, without instance IDs.
  315. *
  316. * @since 2.6.2
  317. * @return string[]
  318. */
  319. function wc_get_chosen_shipping_method_ids() {
  320. $method_ids = array();
  321. $chosen_methods = WC()->session->get( 'chosen_shipping_methods', array() );
  322. foreach ( $chosen_methods as $chosen_method ) {
  323. $chosen_method = explode( ':', $chosen_method );
  324. $method_ids[] = current( $chosen_method );
  325. }
  326. return $method_ids;
  327. }
  328. /**
  329. * Get chosen method for package from session.
  330. *
  331. * @since 3.2.0
  332. * @param int $key Key of package.
  333. * @param array $package Package data array.
  334. * @return string|bool
  335. */
  336. function wc_get_chosen_shipping_method_for_package( $key, $package ) {
  337. $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
  338. $chosen_method = isset( $chosen_methods[ $key ] ) ? $chosen_methods[ $key ] : false;
  339. $changed = wc_shipping_methods_have_changed( $key, $package );
  340. // This is deprecated but here for BW compat. TODO: Remove in 4.0.0.
  341. $method_counts = WC()->session->get( 'shipping_method_counts' );
  342. if ( ! empty( $method_counts[ $key ] ) ) {
  343. $method_count = absint( $method_counts[ $key ] );
  344. } else {
  345. $method_count = 0;
  346. }
  347. // If not set, not available, or available methods have changed, set to the DEFAULT option.
  348. if ( ! $chosen_method || $changed || ! isset( $package['rates'][ $chosen_method ] ) || count( $package['rates'] ) !== $method_count ) {
  349. $chosen_method = wc_get_default_shipping_method_for_package( $key, $package, $chosen_method );
  350. $chosen_methods[ $key ] = $chosen_method;
  351. $method_counts[ $key ] = count( $package['rates'] );
  352. WC()->session->set( 'chosen_shipping_methods', $chosen_methods );
  353. WC()->session->set( 'shipping_method_counts', $method_counts );
  354. do_action( 'woocommerce_shipping_method_chosen', $chosen_method );
  355. }
  356. return $chosen_method;
  357. }
  358. /**
  359. * Choose the default method for a package.
  360. *
  361. * @since 3.2.0
  362. * @param int $key Key of package.
  363. * @param array $package Package data array.
  364. * @param string $chosen_method Chosen method id.
  365. * @return string
  366. */
  367. function wc_get_default_shipping_method_for_package( $key, $package, $chosen_method ) {
  368. $rate_keys = array_keys( $package['rates'] );
  369. $default = current( $rate_keys );
  370. $coupons = WC()->cart->get_coupons();
  371. foreach ( $coupons as $coupon ) {
  372. if ( $coupon->get_free_shipping() ) {
  373. foreach ( $rate_keys as $rate_key ) {
  374. if ( 0 === stripos( $rate_key, 'free_shipping' ) ) {
  375. $default = $rate_key;
  376. break;
  377. }
  378. }
  379. break;
  380. }
  381. }
  382. return apply_filters( 'woocommerce_shipping_chosen_method', $default, $package['rates'], $chosen_method );
  383. }
  384. /**
  385. * See if the methods have changed since the last request.
  386. *
  387. * @since 3.2.0
  388. * @param int $key Key of package.
  389. * @param array $package Package data array.
  390. * @return bool
  391. */
  392. function wc_shipping_methods_have_changed( $key, $package ) {
  393. // Lookup previous methods from session.
  394. $previous_shipping_methods = WC()->session->get( 'previous_shipping_methods' );
  395. // Get new and old rates.
  396. $new_rates = array_keys( $package['rates'] );
  397. $prev_rates = isset( $previous_shipping_methods[ $key ] ) ? $previous_shipping_methods[ $key ] : false;
  398. // Update session.
  399. $previous_shipping_methods[ $key ] = $new_rates;
  400. WC()->session->set( 'previous_shipping_methods', $previous_shipping_methods );
  401. return $new_rates !== $prev_rates;
  402. }
  403. /**
  404. * Gets a hash of important product data that when changed should cause cart items to be invalidated.
  405. *
  406. * The woocommerce_cart_item_data_to_validate filter can be used to add custom properties.
  407. *
  408. * @param WC_Product $product Product object.
  409. * @return string
  410. */
  411. function wc_get_cart_item_data_hash( $product ) {
  412. return md5(
  413. wp_json_encode(
  414. apply_filters(
  415. 'woocommerce_cart_item_data_to_validate',
  416. array(
  417. 'type' => $product->get_type(),
  418. 'attributes' => 'variation' === $product->get_type() ? $product->get_variation_attributes() : '',
  419. ),
  420. $product
  421. )
  422. )
  423. );
  424. }