-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathWooCommerce.php
More file actions
1597 lines (1441 loc) · 55.4 KB
/
Copy pathWooCommerce.php
File metadata and controls
1597 lines (1441 loc) · 55.4 KB
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
namespace Netzstrategen\ShopStandards;
use WGM_Template;
use Netzstrategen\WooCommerceMoeve\Integration\CustomerPortal;
/**
* WooCommerce related functionality.
*/
class WooCommerce {
const FIELD_DISCONTINUED_PRODUCTS = '_' . Plugin::PREFIX . '_discontinued_products';
const FIELD_PRICE_COMPARISON_FOCUS = '_' . Plugin::PREFIX . '_price_comparison_focus';
const FIELD_REPRICING_LOWER_ONLY = '_' . Plugin::PREFIX . '_repricing_lower_only';
const FIELD_HIDE_ADD_TO_CART_BUTTON = '_' . Plugin::PREFIX . '_hide_add_to_cart_button';
const FIELD_HIDE_SALE_PERCENTAGE_FLASH_LABEL = '_' . Plugin::PREFIX . '_hide_sale_percentage_flash_label';
const FIELD_SHOW_SALE_PRICE_ONLY = '_' . Plugin::PREFIX . '_show_sale_price_only';
const FIELD_ERP_INVENTORY = '_' . Plugin::PREFIX . '_erp_inventory_id';
const FIELD_GTIN = '_' . Plugin::PREFIX . '_gtin';
const FIELD_BACK_IN_STOCK_DATE = '_' . Plugin::PREFIX . '_back_in_stock_date';
const FIELD_DISABLE_RELATED_PRODUCTS = '_' . Plugin::PREFIX . '_disable_related_products';
const FIELD_PRODUCT_PURCHASING_PRICE = '_'.Plugin::PREFIX.'_purchasing_price';
const FIELD_ORDER_ITEM = '_' . Plugin::PREFIX . '_order_item';
const FIELD_EXCLUSION_COMPARISON = '_' . Plugin::PREFIX . '_exclusion_comparison';
/**
* Init module.
*/
public static function init(): void {
add_filter(Plugin::PREFIX . '/display_custom_product_fields', __CLASS__ . '::get_product_fields');
}
/**
* Gather all custom product fields including their own label.
*/
public static function get_product_fields(array $fields = []): array {
return array_merge($fields, [
self::FIELD_DISCONTINUED_PRODUCTS => __('Discontinued Products', Plugin::L10N),
self::FIELD_PRICE_COMPARISON_FOCUS => __('Focus Product', Plugin::L10N),
self::FIELD_REPRICING_LOWER_ONLY => __('Slow Sellers', Plugin::L10N),
self::FIELD_ORDER_ITEM => __('Order Item', Plugin::L10N),
self::FIELD_HIDE_ADD_TO_CART_BUTTON => __('Hide add to cart button', Plugin::L10N),
self::FIELD_HIDE_SALE_PERCENTAGE_FLASH_LABEL => __('Hide sale percentage bubble', Plugin::L10N),
self::FIELD_SHOW_SALE_PRICE_ONLY => __('Display sale price as normal price', Plugin::L10N),
self::FIELD_ERP_INVENTORY => __('ERP/Inventory ID', Plugin::L10N),
self::FIELD_GTIN => __('Enter the Global Trade Item Number', Plugin::L10N),
self::FIELD_BACK_IN_STOCK_DATE => __('Enter the back in stock date', Plugin::L10N),
self::FIELD_DISABLE_RELATED_PRODUCTS => __('Disable related products', Plugin::L10N),
self::FIELD_PRODUCT_PURCHASING_PRICE => __('Purchasing Price', Plugin::L10N) . ' (' . get_woocommerce_currency_symbol() . ')',
self::FIELD_EXCLUSION_COMPARISON => __('Exclusion of price comparison platforms', Plugin::L10N),
]);
}
/**
* Adds woocommerce specific settings.
*
* @implements woocommerce_get_settings_shop_standards
*/
public static function woocommerce_get_settings_shop_standards(array $settings): array {
$settings[] = [
'type' => 'title',
'name' => __('Coupon settings', Plugin::L10N),
];
$settings[] = [
'type' => 'checkbox',
'id' => '_' . Plugin::L10N . '_disable_coupon_checkout',
'name' => __('Disable coupon input field on checkout page', Plugin::L10N),
];
$settings[] = [
'type' => 'sectionend',
'id' => Plugin::L10N,
];
return $settings;
}
/**
* Adds strike price for variable products above regular product price labels.
*
* @see https://github.com/woocommerce/woocommerce/issues/16169
*
* @implements woocommerce_get_price_html
*/
public static function woocommerce_get_variation_price_html($price, $product) {
if (
$product->get_type() !== 'variable' ||
get_post_meta($product->get_id(), self::FIELD_SHOW_SALE_PRICE_ONLY, TRUE) === 'yes'
) {
return preg_replace('@<\/span>(-)@', ' – ', $price);
}
$sale_prices = [
'min' => $product->get_variation_price('min', TRUE),
'max' => $product->get_variation_price('max', TRUE),
];
$regular_prices = [
'min' => $product->get_variation_regular_price('min', TRUE),
'max' => $product->get_variation_regular_price('max', TRUE),
];
$regular_price = [wc_price($regular_prices['min'])];
if ($regular_prices['min'] !== $regular_prices['max']) {
$regular_price[] = wc_price($regular_prices['max']);
}
$sale_price = [wc_price($sale_prices['min'])];
if ($sale_prices['min'] !== $sale_prices['max']) {
$sale_price[] = wc_price($sale_prices['max']);
}
if (($sale_prices['min'] !== $regular_prices['min'] || $sale_prices['max'] !== $regular_prices['max'])) {
if ($sale_prices['min'] !== $sale_prices['max'] || $regular_prices['min'] !== $regular_prices['max']) {
$price = '<del>' . implode(' – ', $regular_price) . '</del> <ins>' . implode(' – ', $sale_price) . '</ins>';
}
}
return $price;
}
/**
* Remove "From" text prefixed to prices by B2B Market plugin (starting v1.0.6.1).
*
* @implements bm_original_price_html
*/
public static function b2b_remove_prefix($html, $product_id) {
$html = preg_replace('@<span class="b2b-price-prefix">.[^<]*?</span>@', '', $html);
return $html;
}
/**
* Enables revisions for product descriptions.
*
* @implements woocommerce_register_post_type_product
*/
public static function woocommerce_register_post_type_product($args) {
$args['supports'][] = 'revisions';
return $args;
}
/**
* Shows coupon amount on cart totals template.
*
* @implements woocommerce_cart_totals_coupon_label
*/
public static function addCouponAmount($label, $coupon) {
$coupon_types = [
'fixed_cart',
'percent',
'store_credit',
];
$discountType = $coupon->get_discount_type();
if (!in_array($discountType, $coupon_types)) {
return $label;
}
if ($coupon->get_meta('_wjecf_is_auto_coupon') !== 'yes') {
$label .= '<br/>' . $coupon->get_description();
}
$amount = $coupon->get_amount();
if ($discountType === 'percent') {
$amount = $amount . '%';
}
else {
$amount = wc_price($amount);
}
$label .= ' ' . sprintf(__('Coupon value: %s', Plugin::L10N), wp_strip_all_tags($amount));
return $label;
}
/**
* Changes the minimum amount of variations to trigger the AJAX handling.
*
* In the frontend, if a variable product has more than 20 variations, the
* data will be loaded by ajax rather than handled inline.
*
* @see https://woocommerce.wordpress.com/2015/07/13/improving-the-variations-interface-in-2-4/
*
* @implements woocommerce_ajax_variation_threshold
*/
public static function woocommerce_ajax_variation_threshold($qty, $product) {
return 100;
}
/**
* Displays product availabitily status messages.
*
* Status messages are displayed for every product
* whether stock managing is enabled or it's available.
*
* @implements woocommerce_get_availability
*/
public static function woocommerce_get_availability($stock, $product) {
$product->set_manage_stock('yes');
// If low stock threshold is not set at product level, get global option.
// Zero is allowed so just check for empty string as in WooCommerce Core.
// @see https://git.io/Je7ai
if ($product->is_type('variation')) {
$parent_product = wc_get_product($product->get_parent_id());
$low_stock_amount = $parent_product->get_low_stock_amount();
}
else {
$low_stock_amount = $product->get_low_stock_amount();
}
if ($low_stock_amount === '') {
$low_stock_amount = get_option('woocommerce_notify_low_stock_amount');
}
// Check global "Stock display format" option is set to show low stock notices.
$show_low_stock_amount = get_option('woocommerce_stock_format') === 'low_amount';
// is_in_stock() returns true if stock level is zero but backorders allowed.
// If stock level below threshold (but above zero), show "Only x in stock".
// Otherwise, show "In stock" (not shown by WooCommerce by default).
$product_stock_quantity = $product->get_stock_quantity();
if ($product->is_in_stock()) {
$stock['availability'] = __('In stock', 'woocommerce');
$stock['class'] = 'in-stock';
if ($show_low_stock_amount && $product_stock_quantity > 0 && $product_stock_quantity <= $low_stock_amount) {
$stock['availability'] = sprintf(__('Only %s immediately deliverable', Plugin::L10N), $product_stock_quantity);
$stock['class'] = 'low-stock';
}
}
if ($product->backorders_allowed() && $back_in_stock_date = self::getEarliestBackInStock($product)) {
$date_string = static::getFormattedBackInStockDateString($back_in_stock_date);
$stock['availability'] = '<strong>' . sprintf(__('Back in stock %s', Plugin::L10N), $date_string) . '</strong>';
}
return $stock;
}
/**
* Cron event callback to remove outdated back-in-stock product metadata.
*/
public static function cron_remove_back_in_stock() {
global $wpdb;
$ids = $wpdb->get_col($wpdb->prepare("SELECT p.ID FROM {$wpdb->posts} p
INNER JOIN {$wpdb->postmeta} backinstock ON p.ID = backinstock.post_id
LEFT JOIN {$wpdb->postmeta} moeve ON p.ID = moeve.post_id AND moeve.meta_key LIKE %s
WHERE backinstock.meta_key = %s
AND backinstock.meta_value <= %s
AND moeve.meta_id IS NULL", [
'_woocommerce-moeve_id_%',
self::FIELD_BACK_IN_STOCK_DATE,
date('Y-m-d'),
]));
foreach ($ids as $id) {
if ($product = wc_get_product($id)) {
$product->delete_meta_data(self::FIELD_BACK_IN_STOCK_DATE);
$product->save();
}
}
}
/**
* Cron event callback to remove outdated back-in-stock product metadata.
*/
public static function cron_orphan_variants_cleanup() {
global $wpdb;
$orphan_variants_ids = $wpdb->get_col(
"SELECT p.ID
FROM {$wpdb->posts} p
LEFT JOIN {$wpdb->posts} parent ON parent.ID = p.post_parent
WHERE parent.ID IS NULL AND p.post_type = 'product_variation';"
);
if (!empty($orphan_variants_ids)) {
foreach ($orphan_variants_ids as $id) {
if ($product = wc_get_product($id)) {
$product->delete(TRUE);
}
}
}
}
/**
* Changes number of displayed products.
*
* @implement loop_shop_per_page
*/
public static function loop_shop_per_page($cols) {
return 24;
}
/**
* Hides Add to Cart button for products that must not be sold online.
*/
public static function is_purchasable($purchasable, $product) {
$product_id = $product->get_id();
$hide_add_to_cart = get_post_meta($product_id, self::FIELD_HIDE_ADD_TO_CART_BUTTON, TRUE);
return !wc_string_to_bool($hide_add_to_cart);
}
/**
* Hides sale percentage label.
*
* @param string $output
* The sale label HTML output.
* @param int $salePercentage
* The sale percentage value.
* @param \WP_Product $product
* The current WooCommerce product.
*
* @return string
* The modified sale label HTML output.
*/
public static function sale_percentage_output($output, $salePercentage, $product) {
if (get_post_meta($product->get_id(), self::FIELD_HIDE_SALE_PERCENTAGE_FLASH_LABEL, TRUE) === 'yes') {
$output = '';
}
return $output;
}
/**
* Displays custom fields for single products.
*
* @implements woocommerce_product_options_general_product_data
*/
public static function woocommerce_product_options_general_product_data() {
if (ProductFieldsManager::show_field(self::FIELD_BACK_IN_STOCK_DATE)) {
// Back in stock date field.
echo '<div class="options_group show_if_simple show_if_external">';
woocommerce_wp_text_input([
'id' => self::FIELD_BACK_IN_STOCK_DATE,
'type' => 'date',
'label' => __('Back in stock date', Plugin::L10N),
'desc_tip' => true,
'description' => self::get_product_fields()[self::FIELD_BACK_IN_STOCK_DATE],
]);
echo '</div>';
}
if (ProductFieldsManager::show_field(self::FIELD_GTIN)) {
// GTIN field.
echo '<div class="options_group show_if_simple show_if_external">';
woocommerce_wp_text_input([
'id' => self::FIELD_GTIN,
'label' => __('GTIN', Plugin::L10N),
'desc_tip' => 'true',
'description' => self::get_product_fields()[self::FIELD_GTIN],
]);
echo '</div>';
}
if (ProductFieldsManager::show_field(self::FIELD_ERP_INVENTORY)) {
// ERP/Inventory ID field.
echo '<div class="options_group show_if_simple show_if_external">';
woocommerce_wp_text_input([
'id' => self::FIELD_ERP_INVENTORY,
'label' => self::get_product_fields()[self::FIELD_ERP_INVENTORY],
]);
echo '</div>';
}
if (ProductFieldsManager::show_field(self::FIELD_SHOW_SALE_PRICE_ONLY)) {
// Show `sale price only` checkbox.
echo '<div class="options_group">';
woocommerce_wp_checkbox([
'id' => self::FIELD_SHOW_SALE_PRICE_ONLY,
'label' => self::get_product_fields()[self::FIELD_SHOW_SALE_PRICE_ONLY],
]);
echo '</div>';
}
if (ProductFieldsManager::show_field(self::FIELD_HIDE_SALE_PERCENTAGE_FLASH_LABEL)) {
// Hide sale percentage flash label.
echo '<div class="options_group">';
woocommerce_wp_checkbox([
'id' => self::FIELD_HIDE_SALE_PERCENTAGE_FLASH_LABEL,
'label' => self::get_product_fields()[self::FIELD_HIDE_SALE_PERCENTAGE_FLASH_LABEL],
]);
echo '</div>';
}
if (ProductFieldsManager::show_field(self::FIELD_HIDE_ADD_TO_CART_BUTTON)) {
// Hide add to cart button.
echo '<div class="options_group show_if_simple show_if_external">';
woocommerce_wp_checkbox([
'id' => self::FIELD_HIDE_ADD_TO_CART_BUTTON,
'label' => self::get_product_fields()[self::FIELD_HIDE_ADD_TO_CART_BUTTON],
]);
echo '</div>';
}
if (ProductFieldsManager::show_field(self::FIELD_PRICE_COMPARISON_FOCUS)) {
// Price comparison focus product.
echo '<div class="options_group">';
woocommerce_wp_checkbox([
'id' => self::FIELD_PRICE_COMPARISON_FOCUS,
'label' => self::get_product_fields()[self::FIELD_PRICE_COMPARISON_FOCUS],
]);
echo '</div>';
}
if (ProductFieldsManager::show_field(self::FIELD_REPRICING_LOWER_ONLY)) {
// Repricing: Only lower prices.
echo '<div class="options_group">';
woocommerce_wp_checkbox([
'id' => self::FIELD_REPRICING_LOWER_ONLY,
'label' => self::get_product_fields()[self::FIELD_REPRICING_LOWER_ONLY],
]);
echo '</div>';
}
if (ProductFieldsManager::show_field(self::FIELD_ORDER_ITEM)) {
// Order Item
echo '<div class="options_group">';
woocommerce_wp_checkbox([
'id' => self::FIELD_ORDER_ITEM,
'label' => self::get_product_fields()[self::FIELD_ORDER_ITEM],
]);
echo '</div>';
}
if(ProductFieldsManager::show_field(self::FIELD_DISCONTINUED_PRODUCTS)) {
// Discontinued products.
echo '<div class="options_group">';
woocommerce_wp_checkbox([
'id' => self::FIELD_DISCONTINUED_PRODUCTS,
'label' => self::get_product_fields()[self::FIELD_DISCONTINUED_PRODUCTS],
]);
echo '</div>';
}
if(ProductFieldsManager::show_field(self::FIELD_EXCLUSION_COMPARISON)) {
// Exclusion of price comparison platforms.
echo '<div class="options_group">';
woocommerce_wp_checkbox([
'id' => self::FIELD_EXCLUSION_COMPARISON,
'label' => self::get_product_fields()[self::FIELD_EXCLUSION_COMPARISON],
]);
echo '</div>';
}
}
/**
* Displays custom fields in the Linked Products tab.
*
* @implements woocommerce_product_options_related
*/
public static function woocommerce_product_options_related(): void {
if (ProductFieldsManager::show_field(self::FIELD_DISABLE_RELATED_PRODUCTS)) {
echo '<div class="options_group">';
woocommerce_wp_checkbox([
'id' => self::FIELD_DISABLE_RELATED_PRODUCTS,
'label' => self::get_product_fields()[self::FIELD_DISABLE_RELATED_PRODUCTS],
]);
echo '</div>';
}
}
/**
* Adds pricing custom fields.
*
* @implements woocommerce_product_options_pricing
*/
public static function woocommerce_product_options_pricing() {
if (ProductFieldsManager::show_field(self::FIELD_PRODUCT_PURCHASING_PRICE)) {
woocommerce_wp_text_input([
'id' => self::FIELD_PRODUCT_PURCHASING_PRICE,
'class' => 'wc_input_price short',
'label' => self::get_product_fields()[self::FIELD_PRODUCT_PURCHASING_PRICE],
]);
}
}
/**
* Adds product notes custom field.
*
* This field will be added as the last field in the product
* general options section.
*
* @implements woocommerce_product_options_general_product_data
*/
public static function productNotesCustomField() {
echo '<div class="options_group show_if_simple show_if_variable show_if_external">';
woocommerce_wp_textarea_input([
'id' => '_' . Plugin::PREFIX . '_product_notes',
'label' => __('Internal product notes', Plugin::L10N),
'style' => 'min-height: 120px;',
]);
echo '</div>';
}
/**
* Saves custom fields for simple products.
*
* @implements woocommerce_process_product_meta
*/
public static function woocommerce_process_product_meta($post_id) {
$custom_fields = [
self::FIELD_BACK_IN_STOCK_DATE,
self::FIELD_GTIN,
self::FIELD_ERP_INVENTORY,
'_' . Plugin::PREFIX . '_product_notes',
self::FIELD_PRODUCT_PURCHASING_PRICE,
self::FIELD_DISABLE_RELATED_PRODUCTS,
];
foreach ($custom_fields as $field) {
if (isset($_POST[$field])) {
if (!is_array($_POST[$field]) && $_POST[$field]) {
if ($field !== self::FIELD_GTIN) {
update_post_meta($post_id, $field, $_POST[$field]);
}
else {
$found_duplicate = self::is_existing_gtin($post_id, $_POST[$field]);
if (!$found_duplicate) {
// GTIN is only saved if unique.
update_post_meta($post_id, $field, $_POST[$field]);
}
else {
static::showDuplicateGtinErrorNotice($found_duplicate);
}
}
}
else {
delete_post_meta($post_id, $field);
}
}
}
$custom_fields_checkbox = [
self::FIELD_SHOW_SALE_PRICE_ONLY,
self::FIELD_HIDE_ADD_TO_CART_BUTTON,
self::FIELD_PRICE_COMPARISON_FOCUS,
self::FIELD_REPRICING_LOWER_ONLY,
self::FIELD_HIDE_SALE_PERCENTAGE_FLASH_LABEL,
self::FIELD_DISABLE_RELATED_PRODUCTS,
self::FIELD_ORDER_ITEM,
self::FIELD_DISCONTINUED_PRODUCTS,
self::FIELD_EXCLUSION_COMPARISON,
];
foreach ($custom_fields_checkbox as $field) {
$value = isset($_POST[$field]) && !is_array($_POST[$field]) && wc_string_to_bool($_POST[$field]) ? 'yes' : 'no';
update_post_meta($post_id, $field, $value);
}
}
/**
* Ensures new product are saved before updating its meta data.
*
* New products are still not saved when updated_post_meta hook is called.
* Since we can not check if the meta keys were changed before running
* our custom functions (see updateDeliveryTime),
* we are forcing the post to be saved before updating the meta keys.
*
* @implements woocommerce_process_product_meta
*/
public static function saveNewProductBeforeMetaUpdate($post_id) {
$product = wc_get_product($post_id);
$product->save();
}
/*
* Adds CSS override to wp_head.
*
* @implements wp_head
*/
public static function wp_head() {
global $post;
// Hide Add to Cart button for variable products of specific brands.
// The button is always visible also if no variant is selected.
// If the product has a specific brand, the style gets overridden to hide the button again.
if ($post && static::productHasSpecificTaxonomyTerm($post->ID, 'product_brand')) {
echo '<style>.single_variation_wrap .variations_button { display: none; }</style>';
}
}
/*
* Adds preload tag for main product image to improve largest contentful paint.
*
* @implements wp_head
*/
public static function preloadMainProductImage() {
global $post;
if (!$post || !$post->post_type === 'product') {
return;
}
$image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'woocommerce_single');
if ($image) {
echo '<link rel="preload" href="' . $image[0] . '" as="image">';
}
}
/**
* Hides 'add to cart' button for products from specific categories or brands.
*
* @implements wp
*/
public static function wp() {
if (!is_callable('wc_get_product') || empty($product = wc_get_product())) {
return;
}
$product_id = $product->get_id();
if (static::productHasSpecificTaxonomyTerm($product_id, 'product_cat') || static::productHasSpecificTaxonomyTerm($product_id, 'product_brand')) {
// If the product is a variation, to preserve the variation dropdown
// select, we need to remove the single variation add to cart button.
if ($product->is_type('variable')) {
remove_action('woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20);
}
else {
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
}
}
}
/**
* Displays order notice for products that must not be sold online.
*/
public static function woocommerce_single_product_summary() {
if (function_exists('get_field') && empty($notice = get_field('acf_hide_add_to_cart_product_notice', 'option')) || empty($product = wc_get_product())) {
return;
}
$product_id = $product->get_id();
if (static::productHasSpecificTaxonomyTerm($product_id, 'product_cat') || static::productHasSpecificTaxonomyTerm($product_id, 'product_brand')) {
echo '<div class="info-notice">' . $notice . '</div>';
}
}
/**
* Checks whether a given post has a given term.
*/
public static function productHasSpecificTaxonomyTerm($post_id, $taxonomy_name) {
if (function_exists('get_field') && $excluded_terms = get_field('acf_hide_add_to_cart_' . $taxonomy_name, 'option')) {
return has_term($excluded_terms, $taxonomy_name, $post_id);
}
}
/**
* Creates custom fields for product variations.
*
* @implements woocommerce_product_after_variable_attributes
*/
public static function woocommerce_product_after_variable_attributes($loop, $variation_id, $variation) {
// Variation back in stock date field.
echo '<div style="clear:both">';
woocommerce_wp_text_input([
'id' => '_' . Plugin::PREFIX . '_back_in_stock_date[' . $loop . ']',
'type' => 'date',
'label' => __('Back in stock date', Plugin::L10N),
'desc_tip' => TRUE,
'description' => __('Enter the back in stock date', Plugin::L10N),
'value' => get_post_meta($variation->ID, self::FIELD_BACK_IN_STOCK_DATE, TRUE),
]);
echo '</div>';
// Variation GTIN field.
echo '<div style="clear:both">';
woocommerce_wp_text_input([
'id' => '_' . Plugin::PREFIX . '_gtin[' . $loop . ']',
'label' => __('GTIN:', Plugin::L10N),
'placeholder' => __('Enter the Global Trade Item Number', Plugin::L10N),
'value' => get_post_meta($variation->ID, self::FIELD_GTIN, TRUE),
]);
echo '</div>';
// Variation ERP/Inventory ID field.
echo '<div style="clear:both">';
woocommerce_wp_text_input([
'id' => '_' . Plugin::PREFIX . '_erp_inventory_id[' . $loop . ']',
'label' => __('ERP/Inventory ID:', Plugin::L10N),
'value' => get_post_meta($variation->ID, self::FIELD_ERP_INVENTORY, TRUE),
]);
echo '</div>';
// Variation hide add to cart button.
echo '<div style="clear:both">';
woocommerce_wp_checkbox([
'id' => '_' . Plugin::PREFIX . '_hide_add_to_cart_button_' . $variation->ID,
'label' => __('Hide add to cart button', Plugin::L10N),
'value' => get_post_meta($variation->ID, self::FIELD_HIDE_ADD_TO_CART_BUTTON, TRUE),
]);
echo '</div>';
// Insufficient variant images button checkbox.
echo '<div style="clear:both">';
woocommerce_wp_checkbox([
'id' => '_' . Plugin::PREFIX . '_insufficient_variant_images_' . $variation->ID,
'label' => __('Variation has insufficient images', Plugin::L10N),
'value' => get_post_meta($variation->ID, '_' . Plugin::PREFIX . '_insufficient_variant_images', TRUE),
'description' => __('Allows this product to be identified and possibly be excluded by other processes and plugins (e.g. a custom filter for product feeds). Enabling this option has no effect on the output (by default).', Plugin::L10N),
'desc_tip' => TRUE,
]);
echo '</div>';
if (ProductFieldsManager::show_field(self::FIELD_PRICE_COMPARISON_FOCUS)) {
// Price comparison focus product.
echo '<div style="clear:both">';
woocommerce_wp_checkbox([
'id' => self::FIELD_PRICE_COMPARISON_FOCUS,
'label' => self::get_product_fields()[self::FIELD_PRICE_COMPARISON_FOCUS],
'value' => get_post_meta($variation->ID,
self::FIELD_PRICE_COMPARISON_FOCUS, true),
]);
echo '</div>';
}
if (ProductFieldsManager::show_field(self::FIELD_REPRICING_LOWER_ONLY)) {
// Price comparison focus product.
echo '<div style="clear:both">';
woocommerce_wp_checkbox([
'id' => self::FIELD_REPRICING_LOWER_ONLY,
'label' => self::get_product_fields()[self::FIELD_REPRICING_LOWER_ONLY],
'value' => get_post_meta($variation->ID,
self::FIELD_REPRICING_LOWER_ONLY, true),
]);
echo '</div>';
}
if (ProductFieldsManager::show_field(self::FIELD_ORDER_ITEM)) {
// Order Item
echo '<div class="options_group">';
woocommerce_wp_checkbox([
'id' => self::FIELD_ORDER_ITEM,
'label' => self::get_product_fields()[self::FIELD_ORDER_ITEM],
'value' => get_post_meta($variation->ID, self::FIELD_ORDER_ITEM,
true),
]);
echo '</div>';
}
if (ProductFieldsManager::show_field(self::FIELD_DISCONTINUED_PRODUCTS)) {
// Discontinued products.
echo '<div class="options_group">';
woocommerce_wp_checkbox([
'id' => self::FIELD_DISCONTINUED_PRODUCTS,
'label' => self::get_product_fields()[self::FIELD_DISCONTINUED_PRODUCTS],
'value' => get_post_meta($variation->ID, self::FIELD_DISCONTINUED_PRODUCTS, true),
]);
echo '</div>';
}
if (ProductFieldsManager::show_field(self::FIELD_EXCLUSION_COMPARISON)) {
// Exclusion of price comparison platforms.
echo '<div class="options_group">';
woocommerce_wp_checkbox([
'id' => self::FIELD_EXCLUSION_COMPARISON,
'label' => self::get_product_fields()[self::FIELD_EXCLUSION_COMPARISON],
'value' => get_post_meta($variation->ID, self::FIELD_EXCLUSION_COMPARISON, true),
]);
echo '</div>';
}
}
/**
* Adds pricing custom fields for product variations.
*
* @implements woocommerce_variation_options_pricing
*/
public static function woocommerce_variation_options_pricing($loop, $variation_data, $variation) {
if (ProductFieldsManager::show_field(self::FIELD_PRODUCT_PURCHASING_PRICE)) {
woocommerce_wp_text_input([
'id' => self::FIELD_PRODUCT_PURCHASING_PRICE.'['.$loop.']',
'class' => 'wc_input_price short form-row',
'wrapper_class' => 'form-row',
'label' => self::get_product_fields()[self::FIELD_PRODUCT_PURCHASING_PRICE],
'value' => get_post_meta($variation->ID,
self::FIELD_PRODUCT_PURCHASING_PRICE, true),
]);
}
}
/**
* Saves custom fields for product variations.
*
* @implements woocommerce_save_product_variation
*/
public static function woocommerce_save_product_variation($post_id, $loop) {
if (!isset($_POST['variable_post_id'])) {
return;
}
$variation_id = $_POST['variable_post_id'][$loop];
$custom_fields = [
self::FIELD_BACK_IN_STOCK_DATE,
self::FIELD_GTIN,
self::FIELD_ERP_INVENTORY,
self::FIELD_PRODUCT_PURCHASING_PRICE,
];
foreach ($custom_fields as $field) {
if (isset($_POST[$field]) && isset($_POST[$field][$loop])) {
if ($_POST[$field][$loop]) {
if ($field !== self::FIELD_GTIN) {
update_post_meta($variation_id, $field, $_POST[$field][$loop]);
}
else {
$found_duplicate = self::is_existing_gtin($variation_id, $_POST[$field][$loop]);
if (!$found_duplicate) {
// GTIN is only saved if unique.
update_post_meta($variation_id, $field, $_POST[$field][$loop]);
}
else {
static::showDuplicateGtinErrorNotice($found_duplicate);
}
}
}
else {
delete_post_meta($variation_id, $field);
}
}
}
// Hide add to cart button.
$hide_add_to_cart_button = isset($_POST['_' . Plugin::PREFIX . '_hide_add_to_cart_button_' . $variation_id]) && wc_string_to_bool($_POST['_' . Plugin::PREFIX . '_hide_add_to_cart_button_' . $variation_id]) ? 'yes' : 'no';
update_post_meta($variation_id, self::FIELD_HIDE_ADD_TO_CART_BUTTON, $hide_add_to_cart_button);
// Insufficient images checkbox.
$insufficient_variant_images = isset($_POST['_' . Plugin::PREFIX . '_insufficient_variant_images_' . $variation_id]) && wc_string_to_bool($_POST['_' . Plugin::PREFIX . '_insufficient_variant_images_' . $variation_id]) ? 'yes' : 'no';
update_post_meta($variation_id, '_' . Plugin::PREFIX . '_insufficient_variant_images', $insufficient_variant_images);
// Price comparison focus product.
$price_comparison_focus = isset($_POST[self::FIELD_PRICE_COMPARISON_FOCUS]) && wc_string_to_bool($_POST[self::FIELD_PRICE_COMPARISON_FOCUS]) ? 'yes' : 'no';
update_post_meta($variation_id, self::FIELD_PRICE_COMPARISON_FOCUS, $price_comparison_focus);
// Repricing: Only lower prices.
$price_comparison_lower_only = isset($_POST[self::FIELD_REPRICING_LOWER_ONLY]) && wc_string_to_bool($_POST[self::FIELD_REPRICING_LOWER_ONLY]) ? 'yes' : 'no';
update_post_meta($variation_id, self::FIELD_REPRICING_LOWER_ONLY, $price_comparison_lower_only);
// Order Item
$orderItemFieldValue = isset($_POST[self::FIELD_ORDER_ITEM]) && wc_string_to_bool($_POST[self::FIELD_ORDER_ITEM]) ? 'yes' : 'no';
update_post_meta($variation_id, self::FIELD_ORDER_ITEM, $orderItemFieldValue);
// Discontinued products.
$discontinuedProductsFieldValue = isset($_POST[self::FIELD_DISCONTINUED_PRODUCTS]) && wc_string_to_bool($_POST[self::FIELD_DISCONTINUED_PRODUCTS]) ? 'yes' : 'no';
update_post_meta($variation_id, self::FIELD_DISCONTINUED_PRODUCTS, $discontinuedProductsFieldValue);
// Exclusion of price comparison platforms.
$exclusionComparisonFieldValue = isset($_POST[self::FIELD_EXCLUSION_COMPARISON]) && wc_string_to_bool($_POST[self::FIELD_EXCLUSION_COMPARISON]) ? 'yes' : 'no';
update_post_meta($variation_id, self::FIELD_EXCLUSION_COMPARISON, $exclusionComparisonFieldValue);
}
/**
* Allows adding multiple products to the cart.
*
* See https://bit.ly/3JfcIET
*
* @implements wp_loaded
*/
public static function add_multiple_products_to_cart() {
if (
!isset($_REQUEST['add-to-cart']) ||
strpos($_REQUEST['add-to-cart'], ',') === FALSE
) {
return;
}
$product_ids = explode(',', sanitize_text_field(wp_unslash($_REQUEST['add-to-cart'])));
if (!$product_ids) {
return;
}
remove_action('wp_loaded', array('WC_Form_Handler', 'add_to_cart_action'), 20);
// Avoid redirection to cart after adding a product.
$fn_return_no = fn() => 'no';
add_filter('woocommerce_add_to_cart_redirect', '__return_false', 99);
add_filter('option_woocommerce_cart_redirect_after_add', $fn_return_no, 99);
foreach ($product_ids as $index => $product_id) {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($product_id));
if (empty($product_id)) {
continue;
}
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', TRUE, $product_id, 1);
if (!$passed_validation) {
continue;
}
// Add product to cart
$_REQUEST['add-to-cart'] = $product_id;
\WC_Form_Handler::add_to_cart_action();
}
remove_filter('woocommerce_add_to_cart_redirect', '__return_false', 99);
remove_filter('option_woocommerce_cart_redirect_after_add', $fn_return_no, 99);
}
/**
* Displays sale price as regular price if custom field is checked.
*
* @implements woocommerce_get_price_html
*/
public static function woocommerce_get_price_html($price, $product) {
$product_id = $product->get_type() === 'variation' ? $product->get_parent_id() : $product->get_id();
if (get_post_meta($product_id, self::FIELD_SHOW_SALE_PRICE_ONLY, TRUE) === 'yes') {
if ($product->get_type() === 'variable') {
if ($product->get_variation_sale_price() === $product->get_variation_regular_price()) {
return $price;
}
$sale_prices = [
'min' => $product->get_variation_price('min', TRUE),
'max' => $product->get_variation_price('max', TRUE),
];
$sale_price = [wc_price($sale_prices['min'])];
if ($sale_prices['min'] !== $sale_prices['max']) {
$sale_price[] = wc_price($sale_prices['max']);
}
$price = implode('-', $sale_price);
}
else {
if (!$product->get_sale_price()) {
return $price;
}
$price = wc_price(wc_get_price_to_display($product)) . $product->get_price_suffix();
}
}
return $price;
}
/**
* Checks if displayed product is a related, cross-sell or up-sell product.
*
* @return bool
* TRUE is current displayed product is related, cross-sell or up-sell.
*/
public static function isSideProduct() {
global $woocommerce_loop;
// For the main product in the product single view, $woocommerce_loop['name']
// value is 'up-sells'. We can only detect it is the main product checking
// that $woocommerce_loop['loop'] value is 1.
if (isset($woocommerce_loop['loop']) && $woocommerce_loop['loop'] === 1) {
return FALSE;
}
// At this point we have discarded the main product. Only side products like
// related, cross-sells and up-sells should remain.
if (isset($woocommerce_loop['name']) && in_array($woocommerce_loop['name'], ['related', 'cross-sells', 'up-sells'])) {
return TRUE;
}
return FALSE;
}
/**
* Adds basic information (e.g. weight, sku, etc.) and product attributes to cart item data.
*
* @implements woocommerce_get_item_data
*/
public static function woocommerce_get_item_data($data, $cartItem) {
$product = ($cartItem['variation_id']) ? wc_get_product($cartItem['variation_id']) : wc_get_product($cartItem['product_id']);
// Discard the product variation attributes already included in the parent product data to avoid duplicates.
$stringified_data = serialize($data);
$filtered_attributes = array_filter(static::getProductAttributes($product), function ($item) use ($stringified_data) {
return strpos($stringified_data, '"' . $item['name'] . '"') === FALSE;
});
$separator = [[
'key' => 'separator',
'value' => '',
]];
// Display delivery time from woocommerce-german-market first for each order item.
// Adds a separator element before the attributes list of each order item.
if (count($data) > 1) {
$found = FALSE;
for ($pos = 0; $pos < count($data); $pos++) {
if (in_array(__('Delivery Time', 'woocommerce-german-market'), $data[$pos], TRUE)) {
$found = TRUE;
break;
}
}
if ($found) {
$data = array_merge(array_splice($data, $pos, 1), $separator, $data);
}
}
else {
$data = array_merge($data, $separator);
}
// Add product data (SKU, dimensions and weight) and attributes.
// Note: we display parent attributes for production variations.
$product_data_set = array_merge(static::getProductData($product), $data, $filtered_attributes);
return $product_data_set;
}
/**
* Adds delivery time information to an order item.
*
* @implements woocommerce_new_order_item
*/
public static function add_delivery_time_name_to_order_item($item_id, $item) {
if (!class_exists('WGM_Template')) {
return;
}
if (is_a($item, 'WC_Order_Item_Product')) {
$product = $item->get_product();
$delivery_time_id = apply_filters(
'add_deliverytime_to_order_item',
WGM_Template::get_term_id_from_product_meta('_lieferzeit', $product),
$product
);
if (!empty($delivery_time_id)) {