forked from woocommerce/woocommerce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass-wc-cart.php
2231 lines (1823 loc) · 73.4 KB
/
class-wc-cart.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* WooCommerce cart
*
* The WooCommerce cart class stores cart data and active coupons as well as handling customer sessions and some cart related urls.
* The cart class also has a price calculation function which calls upon other classes to calculate totals.
*
* @class WC_Cart
* @version 2.1.0
* @package WooCommerce/Classes
* @category Class
* @author WooThemes
*/
class WC_Cart {
/** @var array Contains an array of cart items. */
public $cart_contents = array();
/** @var array Contains an array of removed cart items. */
public $removed_cart_contents = array();
/** @var array Contains an array of coupon codes applied to the cart. */
public $applied_coupons = array();
/** @var array Contains an array of coupon code discounts after they have been applied. */
public $coupon_discount_amounts = array();
/** @var array Contains an array of coupon code discount taxes. Used for tax incl pricing. */
public $coupon_discount_tax_amounts = array();
/** @var array Contains an array of coupon usage counts after they have been applied. */
public $coupon_applied_count = array();
/** @var array Array of coupons */
public $coupons = array();
/** @var float The total cost of the cart items. */
public $cart_contents_total;
/** @var float The total weight of the cart items. */
public $cart_contents_weight;
/** @var float The total count of the cart items. */
public $cart_contents_count;
/** @var float Cart grand total. */
public $total;
/** @var float Cart subtotal. */
public $subtotal;
/** @var float Cart subtotal without tax. */
public $subtotal_ex_tax;
/** @var float Total cart tax. */
public $tax_total;
/** @var array An array of taxes/tax rates for the cart. */
public $taxes;
/** @var array An array of taxes/tax rates for the shipping. */
public $shipping_taxes;
/** @var float Discount amount before tax */
public $discount_cart;
/** @var float Discounted tax amount. Used predominantly for displaying tax inclusive prices correctly */
public $discount_cart_tax;
/** @var float Total for additional fees. */
public $fee_total;
/** @var float Shipping cost. */
public $shipping_total;
/** @var float Shipping tax. */
public $shipping_tax_total;
/** @var array cart_session_data. Array of data the cart calculates and stores in the session with defaults */
public $cart_session_data = array(
'cart_contents_total' => 0,
'cart_contents_weight' => 0,
'cart_contents_count' => 0,
'total' => 0,
'subtotal' => 0,
'subtotal_ex_tax' => 0,
'tax_total' => 0,
'taxes' => array(),
'shipping_taxes' => array(),
'discount_cart' => 0,
'discount_cart_tax' => 0,
'shipping_total' => 0,
'shipping_tax_total' => 0,
'coupon_discount_amounts' => array(),
'coupon_discount_tax_amounts' => array(),
'fee_total' => 0,
'fees' => array()
);
/** @var array An array of fees. */
public $fees = array();
/** @var boolean Prices inc tax */
public $prices_include_tax;
/** @var boolean */
public $round_at_subtotal;
/** @var string */
public $tax_display_cart;
/** @var int Prices inc tax */
public $dp;
/** @var boolean */
public $display_totals_ex_tax;
/** @var boolean */
public $display_cart_ex_tax;
/**
* Constructor for the cart class. Loads options and hooks in the init method.
*/
public function __construct() {
$this->prices_include_tax = wc_prices_include_tax();
$this->round_at_subtotal = get_option( 'woocommerce_tax_round_at_subtotal' ) == 'yes';
$this->tax_display_cart = get_option( 'woocommerce_tax_display_cart' );
$this->dp = wc_get_price_decimals();
$this->display_totals_ex_tax = $this->tax_display_cart == 'excl';
$this->display_cart_ex_tax = $this->tax_display_cart == 'excl';
add_action( 'wp_loaded', array( $this, 'init' ) ); // Get cart after WP and plugins are loaded.
add_action( 'wp', array( $this, 'maybe_set_cart_cookies' ), 99 ); // Set cookies
add_action( 'shutdown', array( $this, 'maybe_set_cart_cookies' ), 0 ); // Set cookies before shutdown and ob flushing
add_action( 'woocommerce_add_to_cart', array( $this, 'calculate_totals' ), 20, 0 );
add_action( 'woocommerce_applied_coupon', array( $this, 'calculate_totals' ), 20, 0 );
}
/**
* Auto-load in-accessible properties on demand.
*
* @param mixed $key
* @return mixed
*/
public function __get( $key ) {
switch ( $key ) {
case 'tax':
_deprecated_argument( 'WC_Cart->tax', '2.3', 'Use WC_Tax:: directly' );
$this->tax = new WC_Tax();
return $this->tax;
case 'discount_total':
_deprecated_argument( 'WC_Cart->discount_total', '2.3', 'After tax coupons are no longer supported. For more information see: http://develop.woothemes.com/woocommerce/2014/12/upcoming-coupon-changes-in-woocommerce-2-3/' );
return 0;
}
}
/**
* Loads the cart data from the PHP session during WordPress init and hooks in other methods.
*/
public function init() {
$this->get_cart_from_session();
add_action( 'woocommerce_check_cart_items', array( $this, 'check_cart_items' ), 1 );
add_action( 'woocommerce_check_cart_items', array( $this, 'check_cart_coupons' ), 1 );
add_action( 'woocommerce_after_checkout_validation', array( $this, 'check_customer_coupons' ), 1 );
}
/**
* Will set cart cookies if needed, once, during WP hook
*/
public function maybe_set_cart_cookies() {
if ( ! headers_sent() ) {
if ( sizeof( $this->cart_contents ) > 0 ) {
$this->set_cart_cookies( true );
} elseif ( isset( $_COOKIE['woocommerce_items_in_cart'] ) ) {
$this->set_cart_cookies( false );
}
}
}
/**
* Set cart hash cookie and items in cart.
*
* @access private
* @param bool $set (default: true)
*/
private function set_cart_cookies( $set = true ) {
if ( $set ) {
wc_setcookie( 'woocommerce_items_in_cart', 1 );
wc_setcookie( 'woocommerce_cart_hash', md5( json_encode( $this->get_cart_for_session() ) ) );
} elseif ( isset( $_COOKIE['woocommerce_items_in_cart'] ) ) {
wc_setcookie( 'woocommerce_items_in_cart', 0, time() - HOUR_IN_SECONDS );
wc_setcookie( 'woocommerce_cart_hash', '', time() - HOUR_IN_SECONDS );
}
do_action( 'woocommerce_set_cart_cookies', $set );
}
/*-----------------------------------------------------------------------------------*/
/* Cart Session Handling */
/*-----------------------------------------------------------------------------------*/
/**
* Get the cart data from the PHP session and store it in class variables.
*/
public function get_cart_from_session() {
// Load cart session data from session
foreach ( $this->cart_session_data as $key => $default ) {
$this->$key = WC()->session->get( $key, $default );
}
$update_cart_session = false;
$this->removed_cart_contents = array_filter( WC()->session->get( 'removed_cart_contents', array() ) );
$this->applied_coupons = array_filter( WC()->session->get( 'applied_coupons', array() ) );
/**
* Load the cart object. This defaults to the persistant cart if null.
*/
$cart = WC()->session->get( 'cart', null );
if ( is_null( $cart ) && ( $saved_cart = get_user_meta( get_current_user_id(), '_woocommerce_persistent_cart', true ) ) ) {
$cart = $saved_cart['cart'];
$update_cart_session = true;
} elseif ( is_null( $cart ) ) {
$cart = array();
}
if ( is_array( $cart ) ) {
foreach ( $cart as $key => $values ) {
$_product = wc_get_product( $values['variation_id'] ? $values['variation_id'] : $values['product_id'] );
if ( ! empty( $_product ) && $_product->exists() && $values['quantity'] > 0 ) {
if ( ! $_product->is_purchasable() ) {
// Flag to indicate the stored cart should be update
$update_cart_session = true;
wc_add_notice( sprintf( __( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.', 'woocommerce' ), $_product->get_title() ), 'error' );
do_action( 'woocommerce_remove_cart_item_from_session', $key, $values );
} else {
// Put session data into array. Run through filter so other plugins can load their own session data
$session_data = array_merge( $values, array( 'data' => $_product ) );
$this->cart_contents[ $key ] = apply_filters( 'woocommerce_get_cart_item_from_session', $session_data, $values, $key );
}
}
}
}
if ( $update_cart_session ) {
WC()->session->cart = $this->get_cart_for_session();
}
// Trigger action
do_action( 'woocommerce_cart_loaded_from_session', $this );
// Queue re-calc if subtotal is not set
if ( ( ! $this->subtotal && sizeof( $this->cart_contents ) > 0 ) || $update_cart_session ) {
$this->calculate_totals();
}
}
/**
* Sets the php session data for the cart and coupons.
*/
public function set_session() {
// Set cart and coupon session data
$cart_session = $this->get_cart_for_session();
WC()->session->set( 'cart', $cart_session );
WC()->session->set( 'applied_coupons', $this->applied_coupons );
WC()->session->set( 'coupon_discount_amounts', $this->coupon_discount_amounts );
WC()->session->set( 'coupon_discount_tax_amounts', $this->coupon_discount_tax_amounts );
WC()->session->set( 'removed_cart_contents', $this->removed_cart_contents );
foreach ( $this->cart_session_data as $key => $default ) {
WC()->session->set( $key, $this->$key );
}
if ( get_current_user_id() ) {
$this->persistent_cart_update();
}
do_action( 'woocommerce_cart_updated' );
}
/**
* Empties the cart and optionally the persistent cart too.
*
* @param bool $clear_persistent_cart (default: true)
*/
public function empty_cart( $clear_persistent_cart = true ) {
$this->cart_contents = array();
$this->reset( true );
unset( WC()->session->order_awaiting_payment, WC()->session->applied_coupons, WC()->session->coupon_discount_amounts, WC()->session->coupon_discount_tax_amounts, WC()->session->cart );
if ( $clear_persistent_cart && get_current_user_id() ) {
$this->persistent_cart_destroy();
}
do_action( 'woocommerce_cart_emptied' );
}
/*-----------------------------------------------------------------------------------*/
/* Persistent cart handling */
/*-----------------------------------------------------------------------------------*/
/**
* Save the persistent cart when the cart is updated.
*/
public function persistent_cart_update() {
update_user_meta( get_current_user_id(), '_woocommerce_persistent_cart', array(
'cart' => WC()->session->get( 'cart' )
) );
}
/**
* Delete the persistent cart permanently.
*/
public function persistent_cart_destroy() {
delete_user_meta( get_current_user_id(), '_woocommerce_persistent_cart' );
}
/*-----------------------------------------------------------------------------------*/
/* Cart Data Functions */
/*-----------------------------------------------------------------------------------*/
/**
* Coupons enabled function. Filterable.
*
* @return bool
*/
public function coupons_enabled() {
return apply_filters( 'woocommerce_coupons_enabled', get_option( 'woocommerce_enable_coupons' ) == 'yes' );
}
/**
* Get number of items in the cart.
*
* @return int
*/
public function get_cart_contents_count() {
return apply_filters( 'woocommerce_cart_contents_count', $this->cart_contents_count );
}
/**
* Check all cart items for errors.
*/
public function check_cart_items() {
// Result
$return = true;
// Check cart item validity
$result = $this->check_cart_item_validity();
if ( is_wp_error( $result ) ) {
wc_add_notice( $result->get_error_message(), 'error' );
$return = false;
}
// Check item stock
$result = $this->check_cart_item_stock();
if ( is_wp_error( $result ) ) {
wc_add_notice( $result->get_error_message(), 'error' );
$return = false;
}
return $return;
}
/**
* Check cart coupons for errors.
*/
public function check_cart_coupons() {
foreach ( $this->applied_coupons as $code ) {
$coupon = new WC_Coupon( $code );
if ( ! $coupon->is_valid() ) {
// Error message
$coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_INVALID_REMOVED );
// Remove the coupon
$this->remove_coupon( $code );
// Flag totals for refresh
WC()->session->set( 'refresh_totals', true );
}
}
}
/**
* Get cart items quantities - merged so we can do accurate stock checks on items across multiple lines.
*
* @return array
*/
public function get_cart_item_quantities() {
$quantities = array();
foreach ( $this->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->is_type( 'variation' ) && true === $_product->managing_stock() ) {
// Variation has stock levels defined so its handled individually
$quantities[ $values['variation_id'] ] = isset( $quantities[ $values['variation_id'] ] ) ? $quantities[ $values['variation_id'] ] + $values['quantity'] : $values['quantity'];
} else {
$quantities[ $values['product_id'] ] = isset( $quantities[ $values['product_id'] ] ) ? $quantities[ $values['product_id'] ] + $values['quantity'] : $values['quantity'];
}
}
return $quantities;
}
/**
* Looks through cart items and checks the posts are not trashed or deleted.
*
* @return bool|WP_Error
*/
public function check_cart_item_validity() {
foreach ( $this->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( ! $_product || ! $_product->exists() || $_product->post->post_status == 'trash' ) {
$this->set_quantity( $cart_item_key, 0 );
return new WP_Error( 'invalid', __( 'An item which is no longer available was removed from your cart.', 'woocommerce' ) );
}
}
return true;
}
/**
* Looks through the cart to check each item is in stock. If not, add an error.
*
* @return bool|WP_Error
*/
public function check_cart_item_stock() {
global $wpdb;
$error = new WP_Error();
$product_qty_in_cart = $this->get_cart_item_quantities();
// First stock check loop
foreach ( $this->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
/**
* Check stock based on stock-status
*/
if ( ! $_product->is_in_stock() ) {
$error->add( 'out-of-stock', sprintf(__( 'Sorry, "%s" is not in stock. Please edit your cart and try again. We apologise for any inconvenience caused.', 'woocommerce' ), $_product->get_title() ) );
return $error;
}
if ( ! $_product->managing_stock() ) {
continue;
}
$check_qty = $_product->is_type( 'variation' ) && true === $_product->managing_stock() ? $product_qty_in_cart[ $values['variation_id'] ] : $product_qty_in_cart[ $values['product_id'] ];
/**
* Check stock based on all items in the cart
*/
if ( ! $_product->has_enough_stock( $check_qty ) ) {
$error->add( 'out-of-stock', sprintf(__( 'Sorry, we do not have enough "%s" in stock to fulfill your order (%s in stock). Please edit your cart and try again. We apologise for any inconvenience caused.', 'woocommerce' ), $_product->get_title(), $_product->get_stock_quantity() ) );
return $error;
}
/**
* Finally consider any held stock, from pending orders
*/
if ( get_option( 'woocommerce_hold_stock_minutes' ) > 0 && ! $_product->backorders_allowed() ) {
$order_id = isset( WC()->session->order_awaiting_payment ) ? absint( WC()->session->order_awaiting_payment ) : 0;
$held_stock = $wpdb->get_var(
$wpdb->prepare( "
SELECT SUM( order_item_meta.meta_value ) AS held_qty
FROM {$wpdb->posts} AS posts
LEFT JOIN {$wpdb->prefix}woocommerce_order_items as order_items ON posts.ID = order_items.order_id
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta2 ON order_items.order_item_id = order_item_meta2.order_item_id
WHERE order_item_meta.meta_key = '_qty'
AND order_item_meta2.meta_key = %s AND order_item_meta2.meta_value = %d
AND posts.post_type IN ( '" . implode( "','", wc_get_order_types() ) . "' )
AND posts.post_status = 'wc-pending'
AND posts.ID != %d;",
$_product->is_type( 'variation' ) && true === $_product->managing_stock() ? '_variation_id' : '_product_id',
$_product->is_type( 'variation' ) && true === $_product->managing_stock() ? $values['variation_id'] : $values['product_id'],
$order_id
)
);
$not_enough_stock = false;
if ( $_product->is_type( 'variation' ) && 'parent' === $_product->managing_stock() && $_product->parent->get_stock_quantity() < ( $held_stock + $check_qty ) ) {
$not_enough_stock = true;
} elseif ( $_product->get_stock_quantity() < ( $held_stock + $check_qty ) ) {
$not_enough_stock = true;
}
if ( $not_enough_stock ) {
$error->add( 'out-of-stock', sprintf(__( 'Sorry, we do not have enough "%s" in stock to fulfill your order right now. Please try again in %d minutes or edit your cart and try again. We apologise for any inconvenience caused.', 'woocommerce' ), $_product->get_title(), get_option( 'woocommerce_hold_stock_minutes' ) ) );
return $error;
}
}
}
return true;
}
/**
* Gets and formats a list of cart item data + variations for display on the frontend.
*
* @param array $cart_item
* @param bool $flat (default: false)
* @return string
*/
public function get_item_data( $cart_item, $flat = false ) {
$item_data = array();
// Variation data
if ( ! empty( $cart_item['data']->variation_id ) && is_array( $cart_item['variation'] ) ) {
foreach ( $cart_item['variation'] as $name => $value ) {
if ( '' === $value )
continue;
$taxonomy = wc_attribute_taxonomy_name( str_replace( 'attribute_pa_', '', urldecode( $name ) ) );
// If this is a term slug, get the term's nice name
if ( taxonomy_exists( $taxonomy ) ) {
$term = get_term_by( 'slug', $value, $taxonomy );
if ( ! is_wp_error( $term ) && $term && $term->name ) {
$value = $term->name;
}
$label = wc_attribute_label( $taxonomy );
// If this is a custom option slug, get the options name
} else {
$value = apply_filters( 'woocommerce_variation_option_name', $value );
$product_attributes = $cart_item['data']->get_attributes();
if ( isset( $product_attributes[ str_replace( 'attribute_', '', $name ) ] ) ) {
$label = wc_attribute_label( $product_attributes[ str_replace( 'attribute_', '', $name ) ]['name'] );
} else {
$label = $name;
}
}
$item_data[] = array(
'key' => $label,
'value' => $value
);
}
}
// Other data - returned as array with name/value values
$other_data = apply_filters( 'woocommerce_get_item_data', array(), $cart_item );
if ( $other_data && is_array( $other_data ) && sizeof( $other_data ) > 0 ) {
foreach ( $other_data as $data ) {
// Set hidden to true to not display meta on cart.
if ( empty( $data['hidden'] ) ) {
$display_value = ! empty( $data['display'] ) ? $data['display'] : $data['value'];
$item_data[] = array(
'key' => $data['name'],
'value' => $display_value
);
}
}
}
// Output flat or in list format
if ( sizeof( $item_data ) > 0 ) {
ob_start();
if ( $flat ) {
foreach ( $item_data as $data ) {
echo esc_html( $data['key'] ) . ': ' . wp_kses_post( $data['value'] ) . "\n";
}
} else {
wc_get_template( 'cart/cart-item-data.php', array( 'item_data' => $item_data ) );
}
return ob_get_clean();
}
return '';
}
/**
* Gets cross sells based on the items in the cart.
*
* @return array cross_sells (item ids)
*/
public function get_cross_sells() {
$cross_sells = array();
$in_cart = array();
if ( sizeof( $this->get_cart() ) > 0 ) {
foreach ( $this->get_cart() as $cart_item_key => $values ) {
if ( $values['quantity'] > 0 ) {
$cross_sells = array_merge( $values['data']->get_cross_sells(), $cross_sells );
$in_cart[] = $values['product_id'];
}
}
}
$cross_sells = array_diff( $cross_sells, $in_cart );
return $cross_sells;
}
/**
* Gets the url to the cart page.
*
* @return string url to page
*/
public function get_cart_url() {
$cart_page_id = wc_get_page_id( 'cart' );
return apply_filters( 'woocommerce_get_cart_url', $cart_page_id ? get_permalink( $cart_page_id ) : '' );
}
/**
* Gets the url to the checkout page.
*
* @return string url to page
*/
public function get_checkout_url() {
$checkout_page_id = wc_get_page_id( 'checkout' );
$checkout_url = '';
if ( $checkout_page_id ) {
// Get the checkout URL
$checkout_url = get_permalink( $checkout_page_id );
// Force SSL if needed
if ( is_ssl() || 'yes' === get_option( 'woocommerce_force_ssl_checkout' ) ) {
$checkout_url = str_replace( 'http:', 'https:', $checkout_url );
}
}
return apply_filters( 'woocommerce_get_checkout_url', $checkout_url );
}
/**
* Gets the url to remove an item from the cart.
*
* @param string cart_item_key contains the id of the cart item
* @return string url to page
*/
public function get_remove_url( $cart_item_key ) {
$cart_page_id = wc_get_page_id('cart');
return apply_filters( 'woocommerce_get_remove_url', $cart_page_id ? wp_nonce_url( add_query_arg( 'remove_item', $cart_item_key, get_permalink( $cart_page_id ) ), 'woocommerce-cart' ) : '' );
}
/**
* Gets the url to re-add an item into the cart.
*
* @param string $cart_item_key
* @return string url to page
*/
public function get_undo_url( $cart_item_key ) {
$cart_page_id = wc_get_page_id( 'cart' );
$query_args = array(
'undo_item' => $cart_item_key,
);
return apply_filters( 'woocommerce_get_undo_url', $cart_page_id ? wp_nonce_url( add_query_arg( $query_args, get_permalink( $cart_page_id ) ), 'woocommerce-cart' ) : '' );
}
/**
* Returns the contents of the cart in an array.
*
* @return array contents of the cart
*/
public function get_cart() {
if ( ! did_action( 'wp_loaded' ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Get cart should not be called before the wp_loaded action.', 'woocommerce' ), '2.3' );
}
if ( ! did_action( 'woocommerce_cart_loaded_from_session' ) ) {
$this->get_cart_from_session();
}
return array_filter( (array) $this->cart_contents );
}
/**
* Returns the contents of the cart in an array without the 'data' element.
*
* @return array contents of the cart
*/
public function get_cart_for_session() {
$cart_session = array();
if ( $this->get_cart() ) {
foreach ( $this->get_cart() as $key => $values ) {
$cart_session[ $key ] = $values;
unset( $cart_session[ $key ]['data'] ); // Unset product object
}
}
return $cart_session;
}
/**
* Returns a specific item in the cart
*
* @return array item data
*/
public function get_cart_item( $item_key ) {
if ( isset( $this->cart_contents[ $item_key ] ) ) {
return $this->cart_contents[ $item_key ];
}
return array();
}
/**
* Returns the cart and shipping taxes, merged.
*
* @return array merged taxes
*/
public function get_taxes() {
$taxes = array();
// Merge
foreach ( array_keys( $this->taxes + $this->shipping_taxes ) as $key ) {
$taxes[ $key ] = ( isset( $this->shipping_taxes[ $key ] ) ? $this->shipping_taxes[ $key ] : 0 ) + ( isset( $this->taxes[ $key ] ) ? $this->taxes[ $key ] : 0 );
}
return apply_filters( 'woocommerce_cart_get_taxes', $taxes, $this );
}
/**
* Get taxes, merged by code, formatted ready for output.
*
* @return array
*/
public function get_tax_totals() {
$taxes = $this->get_taxes();
$tax_totals = array();
foreach ( $taxes as $key => $tax ) {
$code = WC_Tax::get_rate_code( $key );
if ( $code || $key === apply_filters( 'woocommerce_cart_remove_taxes_zero_rate_id', 'zero-rated' ) ) {
if ( ! isset( $tax_totals[ $code ] ) ) {
$tax_totals[ $code ] = new stdClass();
$tax_totals[ $code ]->amount = 0;
}
$tax_totals[ $code ]->tax_rate_id = $key;
$tax_totals[ $code ]->is_compound = WC_Tax::is_compound( $key );
$tax_totals[ $code ]->label = WC_Tax::get_rate_label( $key );
$tax_totals[ $code ]->amount += wc_round_tax_total( $tax );
$tax_totals[ $code ]->formatted_amount = wc_price( wc_round_tax_total( $tax_totals[ $code ]->amount ) );
}
}
return apply_filters( 'woocommerce_cart_tax_totals', $tax_totals, $this );
}
/**
* Get all tax classes for items in the cart
* @return array
*/
public function get_cart_item_tax_classes() {
$found_tax_classes = array();
foreach ( WC()->cart->get_cart() as $item ) {
$found_tax_classes[] = $item['data']->get_tax_class();
}
return array_unique( $found_tax_classes );
}
/*-----------------------------------------------------------------------------------*/
/* Add to cart handling */
/*-----------------------------------------------------------------------------------*/
/**
* Check if product is in the cart and return cart item key.
*
* Cart item key will be unique based on the item and its properties, such as variations.
*
* @param mixed id of product to find in the cart
* @return string cart item key
*/
public function find_product_in_cart( $cart_id = false ) {
if ( $cart_id !== false ) {
if ( is_array( $this->cart_contents ) ) {
foreach ( $this->cart_contents as $cart_item_key => $cart_item ) {
if ( $cart_item_key == $cart_id ) {
return $cart_item_key;
}
}
}
}
return '';
}
/**
* Generate a unique ID for the cart item being added.
*
* @param int $product_id - id of the product the key is being generated for
* @param int $variation_id of the product the key is being generated for
* @param array $variation data for the cart item
* @param array $cart_item_data other cart item data passed which affects this items uniqueness in the cart
* @return string cart item key
*/
public function generate_cart_id( $product_id, $variation_id = 0, $variation = array(), $cart_item_data = array() ) {
$id_parts = array( $product_id );
if ( $variation_id && 0 != $variation_id ) {
$id_parts[] = $variation_id;
}
if ( is_array( $variation ) && ! empty( $variation ) ) {
$variation_key = '';
foreach ( $variation as $key => $value ) {
$variation_key .= trim( $key ) . trim( $value );
}
$id_parts[] = $variation_key;
}
if ( is_array( $cart_item_data ) && ! empty( $cart_item_data ) ) {
$cart_item_data_key = '';
foreach ( $cart_item_data as $key => $value ) {
if ( is_array( $value ) ) {
$value = http_build_query( $value );
}
$cart_item_data_key .= trim( $key ) . trim( $value );
}
$id_parts[] = $cart_item_data_key;
}
return md5( implode( '_', $id_parts ) );
}
/**
* Add a product to the cart.
*
* @param integer $product_id contains the id of the product to add to the cart
* @param integer $quantity contains the quantity of the item to add
* @param integer $variation_id
* @param array $variation attribute values
* @param array $cart_item_data extra cart item data we want to pass into the item
* @return string $cart_item_key
*/
public function add_to_cart( $product_id = 0, $quantity = 1, $variation_id = 0, $variation = array(), $cart_item_data = array() ) {
// Wrap in try catch so plugins can throw an exception to prevent adding to cart
try {
$product_id = absint( $product_id );
$variation_id = absint( $variation_id );
// Ensure we don't add a variation to the cart directly by variation ID
if ( 'product_variation' == get_post_type( $product_id ) ) {
$variation_id = $product_id;
$product_id = wp_get_post_parent_id( $variation_id );
}
// Get the product
$product_data = wc_get_product( $variation_id ? $variation_id : $product_id );
// Sanitity check
if ( $quantity <= 0 || ! $product_data || 'trash' === $product_data->post->post_status ) {
throw new Exception();
}
// Load cart item data - may be added by other plugins
$cart_item_data = (array) apply_filters( 'woocommerce_add_cart_item_data', $cart_item_data, $product_id, $variation_id );
// Generate a ID based on product ID, variation ID, variation data, and other cart item data
$cart_id = $this->generate_cart_id( $product_id, $variation_id, $variation, $cart_item_data );
// Find the cart item key in the existing cart
$cart_item_key = $this->find_product_in_cart( $cart_id );
// Force quantity to 1 if sold individually and check for exisitng item in cart
if ( $product_data->is_sold_individually() ) {
$quantity = apply_filters( 'woocommerce_add_to_cart_sold_individually_quantity', 1, $quantity, $product_id, $variation_id, $cart_item_data );
$in_cart_quantity = $cart_item_key ? $this->cart_contents[ $cart_item_key ]['quantity'] : 0;
if ( $in_cart_quantity > 0 ) {
throw new Exception( sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', $this->get_cart_url(), __( 'View Cart', 'woocommerce' ), sprintf( __( 'You cannot add another "%s" to your cart.', 'woocommerce' ), $product_data->get_title() ) ) );
}
}
// Check product is_purchasable
if ( ! $product_data->is_purchasable() ) {
throw new Exception( __( 'Sorry, this product cannot be purchased.', 'woocommerce' ) );
}
// Stock check - only check if we're managing stock and backorders are not allowed
if ( ! $product_data->is_in_stock() ) {
throw new Exception( sprintf( __( 'You cannot add "%s" to the cart because the product is out of stock.', 'woocommerce' ), $product_data->get_title() ) );
}
if ( ! $product_data->has_enough_stock( $quantity ) ) {
throw new Exception( sprintf(__( 'You cannot add that amount of "%s" to the cart because there is not enough stock (%s remaining).', 'woocommerce' ), $product_data->get_title(), $product_data->get_stock_quantity() ) );
}
// Stock check - this time accounting for whats already in-cart
if ( $managing_stock = $product_data->managing_stock() ) {
$products_qty_in_cart = $this->get_cart_item_quantities();
if ( $product_data->is_type( 'variation' ) && true === $managing_stock ) {
$check_qty = isset( $products_qty_in_cart[ $variation_id ] ) ? $products_qty_in_cart[ $variation_id ] : 0;
} else {
$check_qty = isset( $products_qty_in_cart[ $product_id ] ) ? $products_qty_in_cart[ $product_id ] : 0;
}
/**
* Check stock based on all items in the cart
*/
if ( ! $product_data->has_enough_stock( $check_qty + $quantity ) ) {
throw new Exception( sprintf(
'<a href="%s" class="button wc-forward">%s</a> %s',
$this->get_cart_url(),
__( 'View Cart', 'woocommerce' ),
sprintf( __( 'You cannot add that amount to the cart — we have %s in stock and you already have %s in your cart.', 'woocommerce' ), $product_data->get_stock_quantity(), $check_qty )
) );
}
}
// If cart_item_key is set, the item is already in the cart
if ( $cart_item_key ) {
$new_quantity = $quantity + $this->cart_contents[ $cart_item_key ]['quantity'];
$this->set_quantity( $cart_item_key, $new_quantity, false );
} else {
$cart_item_key = $cart_id;
// Add item after merging with $cart_item_data - hook to allow plugins to modify cart item
$this->cart_contents[ $cart_item_key ] = apply_filters( 'woocommerce_add_cart_item', array_merge( $cart_item_data, array(
'product_id' => $product_id,
'variation_id' => $variation_id,
'variation' => $variation,
'quantity' => $quantity,
'data' => $product_data
) ), $cart_item_key );
}
if ( did_action( 'wp' ) ) {
$this->set_cart_cookies( sizeof( $this->cart_contents ) > 0 );
}
do_action( 'woocommerce_add_to_cart', $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data );
return $cart_item_key;
} catch ( Exception $e ) {
if ( $e->getMessage() ) {
wc_add_notice( $e->getMessage(), 'error' );
}
return false;
}
}
/**
* Remove a cart item
*
* @since 2.3.0
* @param string $cart_item_key
* @return bool
*/
public function remove_cart_item( $cart_item_key ) {
if ( isset( $this->cart_contents[ $cart_item_key ] ) ) {
$remove = $this->cart_contents[ $cart_item_key ];
$this->removed_cart_contents[ $cart_item_key ] = $remove;
unset( $this->cart_contents[ $cart_item_key ] );
do_action( 'woocommerce_cart_item_removed', $cart_item_key, $this );
$this->calculate_totals();
return true;
}
return false;
}
/**
* Restore a cart item
*
* @param string $cart_item_key
* @return bool
*/
public function restore_cart_item( $cart_item_key ) {
if ( isset( $this->removed_cart_contents[ $cart_item_key ] ) ) {
$restore = $this->removed_cart_contents[ $cart_item_key ];
$this->cart_contents[ $cart_item_key ] = $restore;
unset( $this->removed_cart_contents[ $cart_item_key ] );