-
Notifications
You must be signed in to change notification settings - Fork 10.7k
/
class-wc-product-data-store-cpt.php
2144 lines (1893 loc) · 70.4 KB
/
class-wc-product-data-store-cpt.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
/**
* WC_Product_Data_Store_CPT class file.
*
* @package WooCommerce\Classes
*/
use Automattic\Jetpack\Constants;
use Automattic\WooCommerce\Internal\DownloadPermissionsAdjuster;
use Automattic\WooCommerce\Utilities\NumberUtil;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* WC Product Data Store: Stored in CPT.
*
* @version 3.0.0
*/
class WC_Product_Data_Store_CPT extends WC_Data_Store_WP implements WC_Object_Data_Store_Interface, WC_Product_Data_Store_Interface {
/**
* Data stored in meta keys, but not considered "meta".
*
* @since 3.0.0
* @var array
*/
protected $internal_meta_keys = array(
'_visibility',
'_sku',
'_price',
'_regular_price',
'_sale_price',
'_sale_price_dates_from',
'_sale_price_dates_to',
'total_sales',
'_tax_status',
'_tax_class',
'_manage_stock',
'_stock',
'_stock_status',
'_backorders',
'_low_stock_amount',
'_sold_individually',
'_weight',
'_length',
'_width',
'_height',
'_upsell_ids',
'_crosssell_ids',
'_purchase_note',
'_default_attributes',
'_product_attributes',
'_virtual',
'_downloadable',
'_download_limit',
'_download_expiry',
'_featured',
'_downloadable_files',
'_wc_rating_count',
'_wc_average_rating',
'_wc_review_count',
'_variation_description',
'_thumbnail_id',
'_file_paths',
'_product_image_gallery',
'_product_version',
'_wp_old_slug',
'_edit_last',
'_edit_lock',
);
/**
* Meta data which should exist in the DB, even if empty.
*
* @since 3.6.0
*
* @var array
*/
protected $must_exist_meta_keys = array(
'_tax_class',
);
/**
* If we have already saved our extra data, don't do automatic / default handling.
*
* @var bool
*/
protected $extra_data_saved = false;
/**
* Stores updated props.
*
* @var array
*/
protected $updated_props = array();
/*
|--------------------------------------------------------------------------
| CRUD Methods
|--------------------------------------------------------------------------
*/
/**
* Method to create a new product in the database.
*
* @param WC_Product $product Product object.
*/
public function create( &$product ) {
if ( ! $product->get_date_created( 'edit' ) ) {
$product->set_date_created( time() );
}
$id = wp_insert_post(
apply_filters(
'woocommerce_new_product_data',
array(
'post_type' => 'product',
'post_status' => $product->get_status() ? $product->get_status() : 'publish',
'post_author' => get_current_user_id(),
'post_title' => $product->get_name() ? $product->get_name() : __( 'Product', 'woocommerce' ),
'post_content' => $product->get_description(),
'post_excerpt' => $product->get_short_description(),
'post_parent' => $product->get_parent_id(),
'comment_status' => $product->get_reviews_allowed() ? 'open' : 'closed',
'ping_status' => 'closed',
'menu_order' => $product->get_menu_order(),
'post_password' => $product->get_post_password( 'edit' ),
'post_date' => gmdate( 'Y-m-d H:i:s', $product->get_date_created( 'edit' )->getOffsetTimestamp() ),
'post_date_gmt' => gmdate( 'Y-m-d H:i:s', $product->get_date_created( 'edit' )->getTimestamp() ),
'post_name' => $product->get_slug( 'edit' ),
)
),
true
);
if ( $id && ! is_wp_error( $id ) ) {
$product->set_id( $id );
$this->update_post_meta( $product, true );
$this->update_terms( $product, true );
$this->update_visibility( $product, true );
$this->update_attributes( $product, true );
$this->update_version_and_type( $product );
$this->handle_updated_props( $product );
$this->clear_caches( $product );
$product->save_meta_data();
$product->apply_changes();
do_action( 'woocommerce_new_product', $id, $product );
}
}
/**
* Method to read a product from the database.
*
* @param WC_Product $product Product object.
* @throws Exception If invalid product.
*/
public function read( &$product ) {
$product->set_defaults();
$post_object = get_post( $product->get_id() );
if ( ! $product->get_id() || ! $post_object || 'product' !== $post_object->post_type ) {
throw new Exception( __( 'Invalid product.', 'woocommerce' ) );
}
$product->set_props(
array(
'name' => $post_object->post_title,
'slug' => $post_object->post_name,
'date_created' => $this->string_to_timestamp( $post_object->post_date_gmt ),
'date_modified' => $this->string_to_timestamp( $post_object->post_modified_gmt ),
'status' => $post_object->post_status,
'description' => $post_object->post_content,
'short_description' => $post_object->post_excerpt,
'parent_id' => $post_object->post_parent,
'menu_order' => $post_object->menu_order,
'post_password' => $post_object->post_password,
'reviews_allowed' => 'open' === $post_object->comment_status,
)
);
$this->read_attributes( $product );
$this->read_downloads( $product );
$this->read_visibility( $product );
$this->read_product_data( $product );
$this->read_extra_data( $product );
$product->set_object_read( true );
do_action( 'woocommerce_product_read', $product->get_id() );
}
/**
* Method to update a product in the database.
*
* @param WC_Product $product Product object.
*/
public function update( &$product ) {
$product->save_meta_data();
$changes = $product->get_changes();
// Only update the post when the post data changes.
if ( array_intersect( array( 'description', 'short_description', 'name', 'parent_id', 'reviews_allowed', 'status', 'menu_order', 'date_created', 'date_modified', 'slug', 'post_password' ), array_keys( $changes ) ) ) {
$post_data = array(
'post_content' => $product->get_description( 'edit' ),
'post_excerpt' => $product->get_short_description( 'edit' ),
'post_title' => $product->get_name( 'edit' ),
'post_parent' => $product->get_parent_id( 'edit' ),
'comment_status' => $product->get_reviews_allowed( 'edit' ) ? 'open' : 'closed',
'post_status' => $product->get_status( 'edit' ) ? $product->get_status( 'edit' ) : 'publish',
'menu_order' => $product->get_menu_order( 'edit' ),
'post_password' => $product->get_post_password( 'edit' ),
'post_name' => $product->get_slug( 'edit' ),
'post_type' => 'product',
);
if ( $product->get_date_created( 'edit' ) ) {
$post_data['post_date'] = gmdate( 'Y-m-d H:i:s', $product->get_date_created( 'edit' )->getOffsetTimestamp() );
$post_data['post_date_gmt'] = gmdate( 'Y-m-d H:i:s', $product->get_date_created( 'edit' )->getTimestamp() );
}
if ( isset( $changes['date_modified'] ) && $product->get_date_modified( 'edit' ) ) {
$post_data['post_modified'] = gmdate( 'Y-m-d H:i:s', $product->get_date_modified( 'edit' )->getOffsetTimestamp() );
$post_data['post_modified_gmt'] = gmdate( 'Y-m-d H:i:s', $product->get_date_modified( 'edit' )->getTimestamp() );
} else {
$post_data['post_modified'] = current_time( 'mysql' );
$post_data['post_modified_gmt'] = current_time( 'mysql', 1 );
}
/**
* When updating this object, to prevent infinite loops, use $wpdb
* to update data, since wp_update_post spawns more calls to the
* save_post action.
*
* This ensures hooks are fired by either WP itself (admin screen save),
* or an update purely from CRUD.
*/
if ( doing_action( 'save_post' ) ) {
$GLOBALS['wpdb']->update( $GLOBALS['wpdb']->posts, $post_data, array( 'ID' => $product->get_id() ) );
clean_post_cache( $product->get_id() );
} else {
wp_update_post( array_merge( array( 'ID' => $product->get_id() ), $post_data ) );
}
$product->read_meta_data( true ); // Refresh internal meta data, in case things were hooked into `save_post` or another WP hook.
} else { // Only update post modified time to record this save event.
$GLOBALS['wpdb']->update(
$GLOBALS['wpdb']->posts,
array(
'post_modified' => current_time( 'mysql' ),
'post_modified_gmt' => current_time( 'mysql', 1 ),
),
array(
'ID' => $product->get_id(),
)
);
clean_post_cache( $product->get_id() );
}
$this->update_post_meta( $product );
$this->update_terms( $product );
$this->update_visibility( $product );
$this->update_attributes( $product );
$this->update_version_and_type( $product );
$this->handle_updated_props( $product );
$this->clear_caches( $product );
wc_get_container()
->get( DownloadPermissionsAdjuster::class )
->maybe_schedule_adjust_download_permissions( $product );
$product->apply_changes();
do_action( 'woocommerce_update_product', $product->get_id(), $product );
}
/**
* Method to delete a product from the database.
*
* @param WC_Product $product Product object.
* @param array $args Array of args to pass to the delete method.
*/
public function delete( &$product, $args = array() ) {
$id = $product->get_id();
$post_type = $product->is_type( 'variation' ) ? 'product_variation' : 'product';
$args = wp_parse_args(
$args,
array(
'force_delete' => false,
)
);
if ( ! $id ) {
return;
}
if ( $args['force_delete'] ) {
do_action( 'woocommerce_before_delete_' . $post_type, $id );
wp_delete_post( $id );
$product->set_id( 0 );
do_action( 'woocommerce_delete_' . $post_type, $id );
} else {
wp_trash_post( $id );
$product->set_status( 'trash' );
do_action( 'woocommerce_trash_' . $post_type, $id );
}
}
/*
|--------------------------------------------------------------------------
| Additional Methods
|--------------------------------------------------------------------------
*/
/**
* Read product data. Can be overridden by child classes to load other props.
*
* @param WC_Product $product Product object.
* @since 3.0.0
*/
protected function read_product_data( &$product ) {
$id = $product->get_id();
$post_meta_values = get_post_meta( $id );
$meta_key_to_props = array(
'_sku' => 'sku',
'_regular_price' => 'regular_price',
'_sale_price' => 'sale_price',
'_price' => 'price',
'_sale_price_dates_from' => 'date_on_sale_from',
'_sale_price_dates_to' => 'date_on_sale_to',
'total_sales' => 'total_sales',
'_tax_status' => 'tax_status',
'_tax_class' => 'tax_class',
'_manage_stock' => 'manage_stock',
'_backorders' => 'backorders',
'_low_stock_amount' => 'low_stock_amount',
'_sold_individually' => 'sold_individually',
'_weight' => 'weight',
'_length' => 'length',
'_width' => 'width',
'_height' => 'height',
'_upsell_ids' => 'upsell_ids',
'_crosssell_ids' => 'cross_sell_ids',
'_purchase_note' => 'purchase_note',
'_default_attributes' => 'default_attributes',
'_virtual' => 'virtual',
'_downloadable' => 'downloadable',
'_download_limit' => 'download_limit',
'_download_expiry' => 'download_expiry',
'_thumbnail_id' => 'image_id',
'_stock' => 'stock_quantity',
'_stock_status' => 'stock_status',
'_wc_average_rating' => 'average_rating',
'_wc_rating_count' => 'rating_counts',
'_wc_review_count' => 'review_count',
'_product_image_gallery' => 'gallery_image_ids',
);
$set_props = array();
foreach ( $meta_key_to_props as $meta_key => $prop ) {
$meta_value = isset( $post_meta_values[ $meta_key ][0] ) ? $post_meta_values[ $meta_key ][0] : null;
$set_props[ $prop ] = maybe_unserialize( $meta_value ); // get_post_meta only unserializes single values.
}
$set_props['category_ids'] = $this->get_term_ids( $product, 'product_cat' );
$set_props['tag_ids'] = $this->get_term_ids( $product, 'product_tag' );
$set_props['shipping_class_id'] = current( $this->get_term_ids( $product, 'product_shipping_class' ) );
$set_props['gallery_image_ids'] = array_filter( explode( ',', $set_props['gallery_image_ids'] ?? '' ) );
$product->set_props( $set_props );
}
/**
* Re-reads stock from the DB ignoring changes.
*
* @param WC_Product $product Product object.
* @param int|float $new_stock New stock level if already read.
*/
public function read_stock_quantity( &$product, $new_stock = null ) {
$object_read = $product->get_object_read();
$product->set_object_read( false ); // This makes update of qty go directly to data- instead of changes-array of the product object (which is needed as the data should hold status of the object as it was read from the db).
$product->set_stock_quantity( is_null( $new_stock ) ? get_post_meta( $product->get_id(), '_stock', true ) : $new_stock );
$product->set_object_read( $object_read );
}
/**
* Read extra data associated with the product, like button text or product URL for external products.
*
* @param WC_Product $product Product object.
* @since 3.0.0
*/
protected function read_extra_data( &$product ) {
foreach ( $product->get_extra_data_keys() as $key ) {
$function = 'set_' . $key;
if ( is_callable( array( $product, $function ) ) ) {
$product->{$function}( get_post_meta( $product->get_id(), '_' . $key, true ) );
}
}
}
/**
* Convert visibility terms to props.
* Catalog visibility valid values are 'visible', 'catalog', 'search', and 'hidden'.
*
* @param WC_Product $product Product object.
* @since 3.0.0
*/
protected function read_visibility( &$product ) {
$terms = get_the_terms( $product->get_id(), 'product_visibility' );
$term_names = is_array( $terms ) ? wp_list_pluck( $terms, 'name' ) : array();
$featured = in_array( 'featured', $term_names, true );
$exclude_search = in_array( 'exclude-from-search', $term_names, true );
$exclude_catalog = in_array( 'exclude-from-catalog', $term_names, true );
if ( $exclude_search && $exclude_catalog ) {
$catalog_visibility = 'hidden';
} elseif ( $exclude_search ) {
$catalog_visibility = 'catalog';
} elseif ( $exclude_catalog ) {
$catalog_visibility = 'search';
} else {
$catalog_visibility = 'visible';
}
$product->set_props(
array(
'featured' => $featured,
'catalog_visibility' => $catalog_visibility,
)
);
}
/**
* Read attributes from post meta.
*
* @param WC_Product $product Product object.
*/
protected function read_attributes( &$product ) {
$meta_attributes = get_post_meta( $product->get_id(), '_product_attributes', true );
if ( ! empty( $meta_attributes ) && is_array( $meta_attributes ) ) {
$attributes = array();
foreach ( $meta_attributes as $meta_attribute_key => $meta_attribute_value ) {
$meta_value = array_merge(
array(
'name' => '',
'value' => '',
'position' => 0,
'is_visible' => 0,
'is_variation' => 0,
'is_taxonomy' => 0,
),
(array) $meta_attribute_value
);
// Check if is a taxonomy attribute.
if ( ! empty( $meta_value['is_taxonomy'] ) ) {
if ( ! taxonomy_exists( $meta_value['name'] ) ) {
continue;
}
$id = wc_attribute_taxonomy_id_by_name( $meta_value['name'] );
$options = wc_get_object_terms( $product->get_id(), $meta_value['name'], 'term_id' );
} else {
$id = 0;
$options = wc_get_text_attributes( $meta_value['value'] );
}
$attribute = new WC_Product_Attribute();
$attribute->set_id( $id );
$attribute->set_name( $meta_value['name'] );
$attribute->set_options( $options );
$attribute->set_position( $meta_value['position'] );
$attribute->set_visible( $meta_value['is_visible'] );
$attribute->set_variation( $meta_value['is_variation'] );
$attributes[] = $attribute;
}
$product->set_attributes( $attributes );
}
}
/**
* Read downloads from post meta.
*
* @param WC_Product $product Product object.
* @since 3.0.0
*/
protected function read_downloads( &$product ) {
$meta_values = array_filter( (array) get_post_meta( $product->get_id(), '_downloadable_files', true ) );
if ( $meta_values ) {
$downloads = array();
foreach ( $meta_values as $key => $value ) {
if ( ! isset( $value['name'], $value['file'] ) ) {
continue;
}
$download = new WC_Product_Download();
$download->set_id( $key );
$download->set_name( $value['name'] ? $value['name'] : wc_get_filename_from_url( $value['file'] ) );
$download->set_file( apply_filters( 'woocommerce_file_download_path', $value['file'], $product, $key ) );
$downloads[] = $download;
}
$product->set_downloads( $downloads );
}
}
/**
* Helper method that updates all the post meta for a product based on it's settings in the WC_Product class.
*
* @param WC_Product $product Product object.
* @param bool $force Force update. Used during create.
* @since 3.0.0
*/
protected function update_post_meta( &$product, $force = false ) {
$meta_key_to_props = array(
'_sku' => 'sku',
'_regular_price' => 'regular_price',
'_sale_price' => 'sale_price',
'_sale_price_dates_from' => 'date_on_sale_from',
'_sale_price_dates_to' => 'date_on_sale_to',
'total_sales' => 'total_sales',
'_tax_status' => 'tax_status',
'_tax_class' => 'tax_class',
'_manage_stock' => 'manage_stock',
'_backorders' => 'backorders',
'_low_stock_amount' => 'low_stock_amount',
'_sold_individually' => 'sold_individually',
'_weight' => 'weight',
'_length' => 'length',
'_width' => 'width',
'_height' => 'height',
'_upsell_ids' => 'upsell_ids',
'_crosssell_ids' => 'cross_sell_ids',
'_purchase_note' => 'purchase_note',
'_default_attributes' => 'default_attributes',
'_virtual' => 'virtual',
'_downloadable' => 'downloadable',
'_product_image_gallery' => 'gallery_image_ids',
'_download_limit' => 'download_limit',
'_download_expiry' => 'download_expiry',
'_thumbnail_id' => 'image_id',
'_stock' => 'stock_quantity',
'_stock_status' => 'stock_status',
'_wc_average_rating' => 'average_rating',
'_wc_rating_count' => 'rating_counts',
'_wc_review_count' => 'review_count',
);
// Make sure to take extra data (like product url or text for external products) into account.
$extra_data_keys = $product->get_extra_data_keys();
foreach ( $extra_data_keys as $key ) {
$meta_key_to_props[ '_' . $key ] = $key;
}
$props_to_update = $force ? $meta_key_to_props : $this->get_props_to_update( $product, $meta_key_to_props );
foreach ( $props_to_update as $meta_key => $prop ) {
$value = $product->{"get_$prop"}( 'edit' );
$value = is_string( $value ) ? wp_slash( $value ) : $value;
switch ( $prop ) {
case 'virtual':
case 'downloadable':
case 'manage_stock':
case 'sold_individually':
$value = wc_bool_to_string( $value );
break;
case 'gallery_image_ids':
$value = implode( ',', $value );
break;
case 'date_on_sale_from':
case 'date_on_sale_to':
$value = $value ? $value->getTimestamp() : '';
break;
case 'stock_quantity':
// Fire actions to let 3rd parties know the stock is about to be changed.
if ( $product->is_type( 'variation' ) ) {
/**
* Action to signal that the value of 'stock_quantity' for a variation is about to change.
*
* @since 4.9
*
* @param int $product The variation whose stock is about to change.
*/
do_action( 'woocommerce_variation_before_set_stock', $product );
} else {
/**
* Action to signal that the value of 'stock_quantity' for a product is about to change.
*
* @since 4.9
*
* @param int $product The product whose stock is about to change.
*/
do_action( 'woocommerce_product_before_set_stock', $product );
}
break;
}
$updated = $this->update_or_delete_post_meta( $product, $meta_key, $value );
if ( $updated ) {
$this->updated_props[] = $prop;
}
}
// Update extra data associated with the product like button text or product URL for external products.
if ( ! $this->extra_data_saved ) {
foreach ( $extra_data_keys as $key ) {
$meta_key = '_' . $key;
$function = 'get_' . $key;
if ( ! array_key_exists( $meta_key, $props_to_update ) ) {
continue;
}
if ( is_callable( array( $product, $function ) ) ) {
$value = $product->{$function}( 'edit' );
$value = is_string( $value ) ? wp_slash( $value ) : $value;
$updated = $this->update_or_delete_post_meta( $product, $meta_key, $value );
if ( $updated ) {
$this->updated_props[] = $key;
}
}
}
}
if ( $this->update_downloads( $product, $force ) ) {
$this->updated_props[] = 'downloads';
}
}
/**
* Handle updated meta props after updating meta data.
*
* @since 3.0.0
* @param WC_Product $product Product Object.
*/
protected function handle_updated_props( &$product ) {
$price_is_synced = $product->is_type( array( 'variable', 'grouped' ) );
if ( ! $price_is_synced ) {
if ( in_array( 'regular_price', $this->updated_props, true ) || in_array( 'sale_price', $this->updated_props, true ) ) {
if ( $product->get_sale_price( 'edit' ) >= $product->get_regular_price( 'edit' ) ) {
update_post_meta( $product->get_id(), '_sale_price', '' );
$product->set_sale_price( '' );
}
}
if ( in_array( 'date_on_sale_from', $this->updated_props, true ) || in_array( 'date_on_sale_to', $this->updated_props, true ) || in_array( 'regular_price', $this->updated_props, true ) || in_array( 'sale_price', $this->updated_props, true ) || in_array( 'product_type', $this->updated_props, true ) ) {
if ( $product->is_on_sale( 'edit' ) ) {
update_post_meta( $product->get_id(), '_price', $product->get_sale_price( 'edit' ) );
$product->set_price( $product->get_sale_price( 'edit' ) );
} else {
update_post_meta( $product->get_id(), '_price', $product->get_regular_price( 'edit' ) );
$product->set_price( $product->get_regular_price( 'edit' ) );
}
}
}
if ( in_array( 'stock_quantity', $this->updated_props, true ) ) {
if ( $product->is_type( 'variation' ) ) {
do_action( 'woocommerce_variation_set_stock', $product );
} else {
do_action( 'woocommerce_product_set_stock', $product );
}
}
if ( in_array( 'stock_status', $this->updated_props, true ) ) {
if ( $product->is_type( 'variation' ) ) {
do_action( 'woocommerce_variation_set_stock_status', $product->get_id(), $product->get_stock_status(), $product );
} else {
do_action( 'woocommerce_product_set_stock_status', $product->get_id(), $product->get_stock_status(), $product );
}
}
if ( array_intersect( $this->updated_props, array( 'sku', 'regular_price', 'sale_price', 'date_on_sale_from', 'date_on_sale_to', 'total_sales', 'average_rating', 'stock_quantity', 'stock_status', 'manage_stock', 'downloadable', 'virtual', 'tax_status', 'tax_class' ) ) ) {
$this->update_lookup_table( $product->get_id(), 'wc_product_meta_lookup' );
}
// Trigger action so 3rd parties can deal with updated props.
do_action( 'woocommerce_product_object_updated_props', $product, $this->updated_props );
// After handling, we can reset the props array.
$this->updated_props = array();
}
/**
* For all stored terms in all taxonomies, save them to the DB.
*
* @param WC_Product $product Product object.
* @param bool $force Force update. Used during create.
* @since 3.0.0
*/
protected function update_terms( &$product, $force = false ) {
$changes = $product->get_changes();
if ( $force || array_key_exists( 'category_ids', $changes ) ) {
$categories = $product->get_category_ids( 'edit' );
if ( empty( $categories ) && get_option( 'default_product_cat', 0 ) ) {
$categories = array( get_option( 'default_product_cat', 0 ) );
}
wp_set_post_terms( $product->get_id(), $categories, 'product_cat', false );
}
if ( $force || array_key_exists( 'tag_ids', $changes ) ) {
wp_set_post_terms( $product->get_id(), $product->get_tag_ids( 'edit' ), 'product_tag', false );
}
if ( $force || array_key_exists( 'shipping_class_id', $changes ) ) {
wp_set_post_terms( $product->get_id(), array( $product->get_shipping_class_id( 'edit' ) ), 'product_shipping_class', false );
}
_wc_recount_terms_by_product( $product->get_id() );
}
/**
* Update visibility terms based on props.
*
* @since 3.0.0
*
* @param WC_Product $product Product object.
* @param bool $force Force update. Used during create.
*/
protected function update_visibility( &$product, $force = false ) {
$changes = $product->get_changes();
if ( $force || array_intersect( array( 'featured', 'stock_status', 'average_rating', 'catalog_visibility' ), array_keys( $changes ) ) ) {
$terms = array();
if ( $product->get_featured() ) {
$terms[] = 'featured';
}
if ( 'outofstock' === $product->get_stock_status() ) {
$terms[] = 'outofstock';
}
$rating = min( 5, NumberUtil::round( $product->get_average_rating(), 0 ) );
if ( $rating > 0 ) {
$terms[] = 'rated-' . $rating;
}
switch ( $product->get_catalog_visibility() ) {
case 'hidden':
$terms[] = 'exclude-from-search';
$terms[] = 'exclude-from-catalog';
break;
case 'catalog':
$terms[] = 'exclude-from-search';
break;
case 'search':
$terms[] = 'exclude-from-catalog';
break;
}
if ( ! is_wp_error( wp_set_post_terms( $product->get_id(), $terms, 'product_visibility', false ) ) ) {
do_action( 'woocommerce_product_set_visibility', $product->get_id(), $product->get_catalog_visibility() );
}
}
}
/**
* Update attributes which are a mix of terms and meta data.
*
* @param WC_Product $product Product object.
* @param bool $force Force update. Used during create.
* @since 3.0.0
*/
protected function update_attributes( &$product, $force = false ) {
$changes = $product->get_changes();
if ( $force || array_key_exists( 'attributes', $changes ) ) {
$attributes = $product->get_attributes();
$meta_values = array();
if ( $attributes ) {
foreach ( $attributes as $attribute_key => $attribute ) {
$value = '';
if ( is_null( $attribute ) ) {
if ( taxonomy_exists( $attribute_key ) ) {
// Handle attributes that have been unset.
wp_set_object_terms( $product->get_id(), array(), $attribute_key );
} elseif ( taxonomy_exists( urldecode( $attribute_key ) ) ) {
// Handle attributes that have been unset.
wp_set_object_terms( $product->get_id(), array(), urldecode( $attribute_key ) );
}
continue;
} elseif ( $attribute->is_taxonomy() ) {
wp_set_object_terms( $product->get_id(), wp_list_pluck( (array) $attribute->get_terms(), 'term_id' ), $attribute->get_name() );
} else {
$value = wc_implode_text_attributes( $attribute->get_options() );
}
// Store in format WC uses in meta.
$meta_values[ $attribute_key ] = array(
'name' => $attribute->get_name(),
'value' => $value,
'position' => $attribute->get_position(),
'is_visible' => $attribute->get_visible() ? 1 : 0,
'is_variation' => $attribute->get_variation() ? 1 : 0,
'is_taxonomy' => $attribute->is_taxonomy() ? 1 : 0,
);
}
}
// Note, we use wp_slash to add extra level of escaping. See https://codex.wordpress.org/Function_Reference/update_post_meta#Workaround.
$this->update_or_delete_post_meta( $product, '_product_attributes', wp_slash( $meta_values ) );
}
}
/**
* Update downloads.
*
* @since 3.0.0
* @param WC_Product $product Product object.
* @param bool $force Force update. Used during create.
* @return bool If updated or not.
*/
protected function update_downloads( &$product, $force = false ) {
$changes = $product->get_changes();
if ( $force || array_key_exists( 'downloads', $changes ) ) {
$downloads = $product->get_downloads();
$meta_values = array();
if ( $downloads ) {
foreach ( $downloads as $key => $download ) {
// Store in format WC uses in meta.
$meta_values[ $key ] = $download->get_data();
}
}
if ( $product->is_type( 'variation' ) ) {
do_action( 'woocommerce_process_product_file_download_paths', $product->get_parent_id(), $product->get_id(), $downloads );
} else {
do_action( 'woocommerce_process_product_file_download_paths', $product->get_id(), 0, $downloads );
}
return $this->update_or_delete_post_meta( $product, '_downloadable_files', wp_slash( $meta_values ) );
}
return false;
}
/**
* Make sure we store the product type and version (to track data changes).
*
* @param WC_Product $product Product object.
* @since 3.0.0
*/
protected function update_version_and_type( &$product ) {
$old_type = WC_Product_Factory::get_product_type( $product->get_id() );
$new_type = $product->get_type();
wp_set_object_terms( $product->get_id(), $new_type, 'product_type' );
update_post_meta( $product->get_id(), '_product_version', Constants::get_constant( 'WC_VERSION' ) );
// Action for the transition.
if ( $old_type !== $new_type ) {
$this->updated_props[] = 'product_type';
do_action( 'woocommerce_product_type_changed', $product, $old_type, $new_type );
}
}
/**
* Clear any caches.
*
* @param WC_Product $product Product object.
* @since 3.0.0
*/
protected function clear_caches( &$product ) {
wc_delete_product_transients( $product->get_id() );
if ( $product->get_parent_id( 'edit' ) ) {
wc_delete_product_transients( $product->get_parent_id( 'edit' ) );
WC_Cache_Helper::invalidate_cache_group( 'product_' . $product->get_parent_id( 'edit' ) );
}
WC_Cache_Helper::invalidate_attribute_count( array_keys( $product->get_attributes() ) );
WC_Cache_Helper::invalidate_cache_group( 'product_' . $product->get_id() );
}
/*
|--------------------------------------------------------------------------
| wc-product-functions.php methods
|--------------------------------------------------------------------------
*/
/**
* Returns an array of on sale products, as an array of objects with an
* ID and parent_id present. Example: $return[0]->id, $return[0]->parent_id.
*
* @return array
* @since 3.0.0
*/
public function get_on_sale_products() {
global $wpdb;
$exclude_term_ids = array();
$outofstock_join = '';
$outofstock_where = '';
$non_published_where = '';
$product_visibility_term_ids = wc_get_product_visibility_term_ids();
if ( 'yes' === get_option( 'woocommerce_hide_out_of_stock_items' ) && $product_visibility_term_ids['outofstock'] ) {
$exclude_term_ids[] = $product_visibility_term_ids['outofstock'];
}
if ( count( $exclude_term_ids ) ) {
$outofstock_join = " LEFT JOIN ( SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id IN ( " . implode( ',', array_map( 'absint', $exclude_term_ids ) ) . ' ) ) AS exclude_join ON exclude_join.object_id = id';
$outofstock_where = ' AND exclude_join.object_id IS NULL';
}
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
return $wpdb->get_results(
"
SELECT posts.ID as id, posts.post_parent as parent_id
FROM {$wpdb->posts} AS posts
INNER JOIN {$wpdb->wc_product_meta_lookup} AS lookup ON posts.ID = lookup.product_id
$outofstock_join
WHERE posts.post_type IN ( 'product', 'product_variation' )
AND posts.post_status = 'publish'
AND lookup.onsale = 1
$outofstock_where
AND posts.post_parent NOT IN (
SELECT ID FROM `$wpdb->posts` as posts
WHERE posts.post_type = 'product'
AND posts.post_parent = 0
AND posts.post_status != 'publish'
)
GROUP BY posts.ID
"
);
// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
}
/**
* Returns a list of product IDs ( id as key => parent as value) that are
* featured. Uses get_posts instead of wc_get_products since we want
* some extra meta queries and ALL products (posts_per_page = -1).
*
* @return array
* @since 3.0.0
*/
public function get_featured_product_ids() {
$product_visibility_term_ids = wc_get_product_visibility_term_ids();
return get_posts(
array(
'post_type' => array( 'product', 'product_variation' ),
'posts_per_page' => -1,
'post_status' => 'publish',
'tax_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
'relation' => 'AND',
array(
'taxonomy' => 'product_visibility',
'field' => 'term_taxonomy_id',
'terms' => array( $product_visibility_term_ids['featured'] ),
),
array(
'taxonomy' => 'product_visibility',
'field' => 'term_taxonomy_id',
'terms' => array( $product_visibility_term_ids['exclude-from-catalog'] ),
'operator' => 'NOT IN',
),
),
'fields' => 'id=>parent',
)
);
}
/**
* Check if product sku is found for any other product IDs.
*
* @since 3.0.0
* @param int $product_id Product ID.
* @param string $sku Will be slashed to work around https://core.trac.wordpress.org/ticket/27421.
* @return bool
*/
public function is_existing_sku( $product_id, $sku ) {
global $wpdb;
// phpcs:ignore WordPress.VIP.DirectDatabaseQuery.DirectQuery
return (bool) $wpdb->get_var(
$wpdb->prepare(
"
SELECT posts.ID
FROM {$wpdb->posts} as posts
INNER JOIN {$wpdb->wc_product_meta_lookup} AS lookup ON posts.ID = lookup.product_id
WHERE
posts.post_type IN ( 'product', 'product_variation' )
AND posts.post_status != 'trash'
AND lookup.sku = %s
AND lookup.product_id <> %d
LIMIT 1
",
wp_slash( $sku ),
$product_id
)
);