-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwinelabel-eu.php
More file actions
810 lines (718 loc) · 25.2 KB
/
Copy pathwinelabel-eu.php
File metadata and controls
810 lines (718 loc) · 25.2 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
<?php
/**
* Plugin Name: WineLabel EU
* Plugin URI: https://winelabel.net
* Description: EU Digital Wine Label — regulation-compliant digital labels (Reg. EU 2021/2117) with ingredients, nutritional values, and waste sorting. Works with or without WooCommerce.
* Version: 1.0.5
* Author: Edoardo Biasini
* Author URI: https://edoardobiasini.com
* Text Domain: winelabel-eu
* Requires at least: 6.0
* Requires PHP: 7.4
* Tested up to: 6.9
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
define( 'WLEU_PATH', plugin_dir_path( __FILE__ ) );
define( 'WLEU_URL', plugin_dir_url( __FILE__ ) );
define( 'WLEU_VERSION', '1.0.5' );
// On activation: flush rewrite rules and clear stale license cache.
register_activation_hook( __FILE__, function () {
delete_transient( 'wleu_license_status' );
// Schedule a flush for after init (when our rewrite rules are registered).
add_option( 'wleu_flush_rewrite', 'yes' );
} );
// Flush rewrite rules once after activation (runs on next page load).
add_action( 'init', function () {
if ( get_option( 'wleu_flush_rewrite' ) === 'yes' ) {
flush_rewrite_rules();
delete_option( 'wleu_flush_rewrite' );
}
}, 99 );
/**
* Load Composer autoloader.
*
* Full version: Carbon Fields + QR code + DomPDF + update checker.
* Lite version (WordPress.org): Carbon Fields only.
*/
if ( file_exists( WLEU_PATH . 'vendor/autoload.php' ) ) {
require_once WLEU_PATH . 'vendor/autoload.php';
}
/**
* Check if the full version (with all Composer deps) is available.
*
* @return bool
*/
function wleu_is_full_version() {
return class_exists( 'Dompdf\\Dompdf' );
}
/**
* Boot Carbon Fields.
*/
add_action( 'after_setup_theme', function () {
\Carbon_Fields\Carbon_Fields::boot();
} );
/**
* Load plugin modules.
*/
require_once WLEU_PATH . 'includes/license.php';
require_once WLEU_PATH . 'includes/limits.php';
require_once WLEU_PATH . 'includes/settings.php';
require_once WLEU_PATH . 'includes/template.php';
require_once WLEU_PATH . 'includes/qr-pdf.php';
require_once WLEU_PATH . 'includes/fields.php';
// ── Auto-Updates (GitHub, full version only) ─────────────────
// Not included in the WordPress.org lite build.
if ( wleu_is_full_version() && class_exists( 'YahnisElsts\\PluginUpdateChecker\\v5\\PucFactory' ) ) {
$wleu_updater = YahnisElsts\PluginUpdateChecker\v5\PucFactory::buildUpdateChecker(
'https://github.com/edoardobiasini/winelabel-eu/',
__FILE__,
'winelabel-eu'
);
$wleu_updater->getVcsApi()->enableReleaseAssets();
}
// ── WooCommerce Soft Dependency ──────────────────────────────
/**
* Check if WooCommerce is active.
*
* @return bool
*/
function wleu_is_woocommerce_active() {
return class_exists( 'WooCommerce' ) || in_array( 'woocommerce/woocommerce.php', (array) get_option( 'active_plugins', [] ), true );
}
/**
* Check if the plugin should use WooCommerce products.
*
* Returns true only when WooCommerce is active AND the user has opted in
* (or hasn't explicitly opted out — defaults to 'yes' for backward compat).
*
* @return bool
*/
function wleu_uses_woocommerce() {
return wleu_is_woocommerce_active() && get_option( 'wleu_use_woocommerce', 'no' ) === 'yes';
}
/**
* Get the post type used for wines/products.
*
* Returns 'product' when WooCommerce integration is enabled, 'wleu_wine' otherwise.
*
* @return string
*/
function wleu_product_post_type() {
return wleu_uses_woocommerce() ? 'product' : 'wleu_wine';
}
// ── Custom Post Type: elabel_vintage ─────────────────────────
/**
* Register the elabel_vintage CPT and, when WooCommerce is absent, the wleu_wine CPT.
*/
add_action( 'init', function () {
register_post_type( 'elabel_vintage', [
'labels' => [
'name' => __( 'Vintages', 'winelabel-eu' ),
'singular_name' => __( 'Vintage', 'winelabel-eu' ),
'add_new' => __( 'Add Vintage', 'winelabel-eu' ),
'add_new_item' => __( 'Add New Vintage', 'winelabel-eu' ),
'edit_item' => __( 'Edit Vintage', 'winelabel-eu' ),
'new_item' => __( 'New Vintage', 'winelabel-eu' ),
'view_item' => __( 'View Vintage', 'winelabel-eu' ),
'search_items' => __( 'Search Vintages', 'winelabel-eu' ),
'not_found' => __( 'No vintages found.', 'winelabel-eu' ),
'not_found_in_trash' => __( 'No vintages found in Trash.', 'winelabel-eu' ),
],
'public' => false,
'show_ui' => true,
'show_in_menu' => false,
'supports' => false,
'has_archive' => false,
'rewrite' => false,
] );
// Standalone wine CPT — when not using WooCommerce integration.
if ( ! wleu_uses_woocommerce() ) {
register_post_type( 'wleu_wine', [
'labels' => [
'name' => __( 'Wines', 'winelabel-eu' ),
'singular_name' => __( 'Wine', 'winelabel-eu' ),
'add_new' => __( 'Add Wine', 'winelabel-eu' ),
'add_new_item' => __( 'Add New Wine', 'winelabel-eu' ),
'edit_item' => __( 'Edit Wine', 'winelabel-eu' ),
'new_item' => __( 'New Wine', 'winelabel-eu' ),
'view_item' => __( 'View Wine', 'winelabel-eu' ),
'search_items' => __( 'Search Wines', 'winelabel-eu' ),
'not_found' => __( 'No wines found.', 'winelabel-eu' ),
'not_found_in_trash' => __( 'No wines found in Trash.', 'winelabel-eu' ),
],
'public' => false,
'publicly_queryable' => false,
'show_ui' => true,
'show_in_menu' => 'winelabel-eu',
'supports' => [ 'title' ],
'has_archive' => false,
'rewrite' => false,
'menu_icon' => 'dashicons-clipboard',
] );
}
} );
/**
* Auto-set post_parent from URL parameter when creating a new vintage.
*/
add_filter( 'wp_insert_post_data', function ( $data, $postarr ) {
if ( $data['post_type'] !== 'elabel_vintage' ) {
return $data;
}
// Set post_parent from URL parameter on new posts.
if ( empty( $postarr['ID'] ) && ! empty( $_GET['parent_product'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- nonce verified by WordPress core post-saving handler.
$data['post_parent'] = absint( $_GET['parent_product'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
}
return $data;
}, 10, 2 );
/**
* Auto-generate vintage post title after Carbon Fields saves its values.
*/
add_action( 'carbon_fields_post_meta_container_saved', function ( $post_id ) {
$post = get_post( $post_id );
if ( ! $post || $post->post_type !== 'elabel_vintage' ) {
return;
}
$annata = carbon_get_post_meta( $post_id, 'elabel_annata' );
$product_id = $post->post_parent;
if ( ! $product_id || ! $annata ) {
return;
}
$new_title = get_the_title( $product_id ) . ' — ' . $annata;
if ( $post->post_title !== $new_title ) {
wp_update_post( [
'ID' => $post_id,
'post_title' => $new_title,
] );
}
} );
// ── Vintage List: Injected into Carbon Fields Container ──────
/**
* Inject the vintage list into the Carbon Fields container
* via an admin footer script that moves the content into place.
*/
add_action( 'add_meta_boxes', function () {
add_meta_box(
'wleu_vintages',
__( 'Vintages', 'winelabel-eu' ),
'wleu_vintages_metabox',
wleu_product_post_type(),
'normal',
'default'
);
} );
/**
* Move the vintage list into the Carbon Fields container via inline JS.
*/
add_action( 'admin_footer', function () {
$screen = get_current_screen();
if ( ! $screen || $screen->post_type !== wleu_product_post_type() ) {
return;
}
?>
<script>
jQuery(function($) {
var $cf = $('#carbon_fields_container_winelabel_eu .fields-container, #carbon_fields_container_winelabel_eu .inside');
var $vintage = $('#wleu_vintages');
if ($cf.length && $vintage.length) {
var $content = $vintage.find('.inside').children();
var $wrapper = $('<div class="elabel-vintages-inline"></div>').append($content);
$cf.first().append($wrapper);
$vintage.remove();
}
});
</script>
<?php
} );
/**
* Render the vintages list (will be moved into Carbon Fields container via JS).
*
* @param WP_Post $post The product post object.
*/
function wleu_vintages_metabox( $post ) {
// Wine must be saved (at least as draft) before vintages can be added.
if ( $post->post_status === 'auto-draft' ) {
?>
<p style="color: #666; padding: 8px 16px;">
<?php esc_html_e( 'Save this wine first (as Draft or Published) to start adding vintages.', 'winelabel-eu' ); ?>
</p>
<?php
return;
}
$vintages = get_posts( [
'post_type' => 'elabel_vintage',
'post_parent' => $post->ID,
'posts_per_page' => -1,
'post_status' => 'any',
'orderby' => 'meta_value',
'meta_key' => '_elabel_annata',
'order' => 'ASC',
] );
$add_url = admin_url( 'post-new.php?post_type=elabel_vintage&parent_product=' . $post->ID );
$at_limit = ! wleu_can_publish_vintage();
// Show the e-label URL if the label is enabled and there are published vintages.
$elabel_enabled = carbon_get_post_meta( $post->ID, 'elabel_enabled' );
$has_published = false;
foreach ( $vintages as $v ) {
if ( $v->post_status === 'publish' ) {
$has_published = true;
break;
}
}
if ( $elabel_enabled && $has_published ) {
$label_url = wleu_label_url( $post->post_name );
printf(
'<p style="margin-bottom: 12px;"><strong>%s:</strong> <a href="%s" target="_blank">%s</a></p>',
esc_html__( 'Label URL', 'winelabel-eu' ),
esc_url( $label_url ),
esc_html( $label_url )
);
}
?>
<style>
.elabel-vintages-inline {
border-top: 1px solid #e0e0e0;
padding: 16px 16px 4px;
margin-top: 12px;
}
.elabel-vintages-inline h3 {
margin: 0 0 10px;
font-size: 14px;
font-weight: 600;
}
.elabel-vintage-table { width: 100%; border-collapse: collapse; }
.elabel-vintage-table th,
.elabel-vintage-table td { padding: 8px 12px; text-align: left; border-bottom: 1px solid #e0e0e0; }
.elabel-vintage-table th { font-weight: 600; font-size: 13px; color: #555; }
.elabel-vintage-table .elabel-actions { font-size: 12px; }
.elabel-vintage-table .elabel-actions a { text-decoration: none; }
.elabel-vintage-table .elabel-actions .sep { color: #ccc; padding: 0 4px; }
.elabel-vintage-table .elabel-actions .delete a { color: #b32d2e; }
.elabel-vintage-table .elabel-actions .delete a:hover { color: #a02020; }
.elabel-vintage-add { margin-top: 12px; }
</style>
<h3><?php esc_html_e( 'Vintages', 'winelabel-eu' ); ?></h3>
<?php if ( ! empty( $vintages ) ) : ?>
<table class="elabel-vintage-table">
<thead>
<tr>
<th><?php esc_html_e( 'Year', 'winelabel-eu' ); ?></th>
<th><?php esc_html_e( 'Title', 'winelabel-eu' ); ?></th>
<th><?php esc_html_e( 'Status', 'winelabel-eu' ); ?></th>
<th><?php esc_html_e( 'Actions', 'winelabel-eu' ); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ( $vintages as $vintage ) :
$annata = carbon_get_post_meta( $vintage->ID, 'elabel_annata' );
$edit_url = get_edit_post_link( $vintage->ID );
$status = get_post_status_object( $vintage->post_status );
?>
<tr>
<td><strong><?php echo esc_html( $annata ?: '—' ); ?></strong></td>
<td><?php echo esc_html( $vintage->post_title ); ?></td>
<td><?php echo esc_html( $status->label ?? $vintage->post_status ); ?></td>
<td class="elabel-actions">
<a href="<?php echo esc_url( $edit_url ); ?>"><?php esc_html_e( 'Edit', 'winelabel-eu' ); ?></a>
<?php if ( wleu_is_pro() ) : ?>
<?php
$dup_url = wp_nonce_url(
admin_url( 'admin.php?action=wleu_duplicate_vintage&post=' . $vintage->ID ),
'wleu_duplicate_vintage_' . $vintage->ID
);
?>
<span class="sep">|</span>
<a href="<?php echo esc_url( $dup_url ); ?>"><?php esc_html_e( 'Duplicate', 'winelabel-eu' ); ?></a>
<?php endif; ?>
<?php
$del_url = wp_nonce_url(
admin_url( 'admin.php?action=wleu_delete_vintage&post=' . $vintage->ID ),
'wleu_delete_vintage_' . $vintage->ID
);
?>
<span class="sep">|</span>
<span class="delete"><a href="<?php echo esc_url( $del_url ); ?>" onclick="return confirm('<?php echo esc_js( __( 'Delete this vintage?', 'winelabel-eu' ) ); ?>');"><?php esc_html_e( 'Delete', 'winelabel-eu' ); ?></a></span>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else : ?>
<p><?php esc_html_e( 'No vintages created. Click the button to add one.', 'winelabel-eu' ); ?></p>
<?php endif; ?>
<p class="elabel-vintage-add">
<?php if ( $at_limit ) : ?>
<button class="button button-primary" disabled title="<?php esc_attr_e( 'Vintage limit reached. Upgrade to Pro for unlimited vintages.', 'winelabel-eu' ); ?>">
<?php esc_html_e( '+ Add Vintage', 'winelabel-eu' ); ?>
</button>
<?php else : ?>
<a href="<?php echo esc_url( $add_url ); ?>" class="button button-primary">
<?php esc_html_e( '+ Add Vintage', 'winelabel-eu' ); ?>
</a>
<?php endif; ?>
</p>
<?php
}
// ── Duplicate Vintage Action (Pro only) ──────────────────────
/**
* Handle the "Duplicate Vintage" admin action.
*/
add_action( 'admin_action_wleu_duplicate_vintage', function () {
if ( ! current_user_can( 'edit_posts' ) ) {
wp_die( esc_html__( 'You do not have permission to perform this action.', 'winelabel-eu' ) );
}
if ( ! wleu_is_pro() ) {
wp_die( esc_html__( 'This feature requires WineLabel EU Pro.', 'winelabel-eu' ) );
}
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- absint() handles sanitization.
$post_id = absint( wp_unslash( $_GET['post'] ?? 0 ) );
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitize_text_field handles sanitization.
if ( ! $post_id || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ?? '' ) ), 'wleu_duplicate_vintage_' . $post_id ) ) {
wp_die( esc_html__( 'Unauthorized action.', 'winelabel-eu' ) );
}
$source = get_post( $post_id );
if ( ! $source || $source->post_type !== 'elabel_vintage' ) {
wp_die( esc_html__( 'Vintage not found.', 'winelabel-eu' ) );
}
$new_id = wp_insert_post( [
'post_type' => 'elabel_vintage',
'post_status' => 'draft',
'post_title' => $source->post_title . ' (copy)',
'post_parent' => $source->post_parent,
] );
if ( is_wp_error( $new_id ) ) {
wp_die( esc_html( $new_id->get_error_message() ) );
}
// Copy all meta from source to new post.
$meta = get_post_meta( $source->ID );
foreach ( $meta as $key => $values ) {
if ( in_array( $key, [ '_edit_lock', '_edit_last' ], true ) ) {
continue;
}
foreach ( $values as $value ) {
add_post_meta( $new_id, $key, maybe_unserialize( $value ) );
}
}
wp_safe_redirect( get_edit_post_link( $new_id, 'raw' ) );
exit;
} );
// ── Delete Vintage Action ────────────────────────────────────
/**
* Handle the "Delete Vintage" admin action.
*/
add_action( 'admin_action_wleu_delete_vintage', function () {
if ( ! current_user_can( 'edit_posts' ) ) {
wp_die( esc_html__( 'You do not have permission to perform this action.', 'winelabel-eu' ) );
}
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- absint() handles sanitization.
$post_id = absint( wp_unslash( $_GET['post'] ?? 0 ) );
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitize_text_field handles sanitization.
if ( ! $post_id || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ?? '' ) ), 'wleu_delete_vintage_' . $post_id ) ) {
wp_die( esc_html__( 'Unauthorized action.', 'winelabel-eu' ) );
}
$post = get_post( $post_id );
if ( ! $post || $post->post_type !== 'elabel_vintage' ) {
wp_die( esc_html__( 'Vintage not found.', 'winelabel-eu' ) );
}
$product_id = $post->post_parent;
wp_delete_post( $post_id, true );
wp_safe_redirect( get_edit_post_link( $product_id, 'raw' ) );
exit;
} );
/**
* Add a "Back to product" link on the vintage edit screen.
*/
add_action( 'edit_form_top', function ( $post ) {
if ( $post->post_type !== 'elabel_vintage' || ! $post->post_parent ) {
return;
}
$product_url = get_edit_post_link( $post->post_parent );
$product_title = get_the_title( $post->post_parent );
printf(
'<div class="notice notice-info" style="padding:10px;margin:10px 0;"><strong>%s:</strong> <a href="%s">%s</a></div>',
esc_html( wleu_uses_woocommerce() ? __( 'Product', 'winelabel-eu' ) : __( 'Wine', 'winelabel-eu' ) ),
esc_url( $product_url ),
esc_html( $product_title )
);
} );
/**
* Get the index page slug.
*
* @return string
*/
function wleu_index_slug() {
return get_option( 'wleu_index_slug', 'winelabel' );
}
/**
* Build a label URL that works with both pretty and plain permalinks.
*
* @param string $product_slug Product slug.
* @param string|null $year Two-digit vintage year, or null for bare label.
* @return string
*/
function wleu_label_url( $product_slug, $year = null ) {
if ( get_option( 'permalink_structure' ) ) {
$path = $product_slug . '-winelabel';
if ( $year ) {
$path .= '-' . $year;
}
return home_url( '/' . $path . '/' );
}
$args = [ 'elabel_product' => $product_slug ];
if ( $year ) {
$args['elabel_year'] = $year;
}
return add_query_arg( $args, home_url( '/' ) );
}
/**
* Build the label index URL that works with both pretty and plain permalinks.
*
* @return string
*/
function wleu_index_url() {
if ( get_option( 'permalink_structure' ) ) {
return home_url( '/' . wleu_index_slug() . '/' );
}
return add_query_arg( 'elabel_index', '1', home_url( '/' ) );
}
// ── Elabel Request Detection ─────────────────────────────────
/**
* Check if the current request is an elabel page.
*
* @return bool
*/
function wleu_is_elabel_request() {
// Query-param format (plain permalinks).
if ( isset( $_GET['elabel_product'] ) || isset( $_GET['elabel_index'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- public frontend URL parameters.
return true;
}
// Pretty URL format.
$uri = sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ?? '' ) );
$uri = trim( $uri, '/' );
$uri = strtok( $uri, '?' );
$index_slug = wleu_index_slug();
return (bool) preg_match( '/^(.+)-winelabel(?:-\d{2})?\/?$/', $uri )
|| $uri === $index_slug;
}
/**
* Disable cookie consent and other tracking plugins on elabel pages.
* Fires early to prevent cookie-setting behaviour.
*/
add_action( 'plugins_loaded', function () {
if ( ! wleu_is_elabel_request() ) {
return;
}
// Prevent cookie-consent plugins from loading.
remove_all_actions( 'wp_enqueue_scripts', 10 );
// Prevent WP from sending cache/cookie headers on these pages.
add_action( 'send_headers', function () {
header_remove( 'Set-Cookie' );
header( 'Cache-Control: public, max-age=86400' );
header( 'X-Robots-Tag: noindex, nofollow' );
}, 999 );
}, 1 );
// ── Rewrite Rules ────────────────────────────────────────────
/**
* Register rewrite rules.
*/
add_action( 'init', function () {
// Vintage-specific label: {product-slug}-winelabel-{YY}/
add_rewrite_rule(
'^([^/]+)-winelabel-(\d{2})/?$',
'index.php?elabel_product=$matches[1]&elabel_year=$matches[2]',
'top'
);
// Bare label (no year): {product-slug}-winelabel/ -> redirect to latest vintage
add_rewrite_rule(
'^([^/]+)-winelabel/?$',
'index.php?elabel_product=$matches[1]',
'top'
);
// Index page: /e-labels/ (slug configurable in settings).
$index_slug = wleu_index_slug();
add_rewrite_rule(
'^' . preg_quote( $index_slug, '/' ) . '/?$',
'index.php?elabel_index=1',
'top'
);
}, 20 );
/**
* Register custom query vars.
*/
add_filter( 'query_vars', function ( $vars ) {
$vars[] = 'elabel_product';
$vars[] = 'elabel_year';
$vars[] = 'elabel_index';
return $vars;
} );
// ── Template Redirect ────────────────────────────────────────
/**
* Intercept requests and render bare HTML templates.
*/
add_action( 'template_redirect', function () {
$product_slug = get_query_var( 'elabel_product' );
$year = get_query_var( 'elabel_year' );
$is_index = get_query_var( 'elabel_index' );
// EN is the default language. Second language (via ?lang=xx) requires Pro.
$lang = 'en';
if ( wleu_is_pro() && isset( $_GET['lang'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- public frontend URL parameter.
$alt_lang = get_option( 'wleu_second_language_code', 'it' );
$requested = sanitize_text_field( wp_unslash( $_GET['lang'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( $requested === $alt_lang ) {
$lang = $alt_lang;
}
}
if ( $product_slug ) {
header_remove( 'Set-Cookie' );
$product_slug = sanitize_title( $product_slug );
// QR code PDF download (Pro only).
if ( isset( $_GET['qr'] ) && sanitize_text_field( wp_unslash( $_GET['qr'] ) ) === 'pdf' ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- public frontend URL parameter.
if ( ! wleu_is_pro() ) {
status_header( 403 );
echo 'QR PDF download requires WineLabel EU Pro.';
exit;
}
wleu_render_elabel_qr_pdf( $product_slug, $year );
exit;
}
// No year specified -> 301 redirect to latest vintage.
if ( empty( $year ) ) {
$latest_year = wleu_get_latest_year( $product_slug );
if ( $latest_year ) {
$redirect_url = wleu_label_url( $product_slug, $latest_year );
if ( $lang !== 'en' ) {
$redirect_url = add_query_arg( 'lang', $lang, $redirect_url );
}
wp_safe_redirect( $redirect_url, 301 );
exit;
}
}
wleu_render_elabel_single( $product_slug, $year, $lang );
exit;
}
if ( $is_index ) {
header_remove( 'Set-Cookie' );
wleu_render_elabel_index( $lang );
exit;
}
} );
// ── Helper Functions ─────────────────────────────────────────
/**
* Get the latest (highest) vintage year for a product slug.
*
* @param string $product_slug Product slug.
* @return string|false Two-digit year string, or false if none found.
*/
function wleu_get_latest_year( $product_slug ) {
$products = get_posts( [
'post_type' => wleu_product_post_type(),
'name' => $product_slug,
'posts_per_page' => 1,
'post_status' => 'publish',
] );
if ( empty( $products ) ) {
return false;
}
$vintages = get_posts( [
'post_type' => 'elabel_vintage',
'post_parent' => $products[0]->ID,
'posts_per_page' => 1,
'post_status' => 'publish',
'orderby' => 'meta_value',
'meta_key' => '_elabel_annata',
'order' => 'DESC',
] );
if ( empty( $vintages ) ) {
return false;
}
return carbon_get_post_meta( $vintages[0]->ID, 'elabel_annata' ) ?: false;
}
/**
* Find a vintage post for a given product ID and year.
*
* @param int $product_id Product post ID.
* @param string $year Two-digit vintage year.
* @return WP_Post|null
*/
function wleu_find_vintage( $product_id, $year ) {
$vintages = get_posts( [
'post_type' => 'elabel_vintage',
'post_parent' => $product_id,
'posts_per_page' => 1,
'post_status' => 'publish',
'meta_query' => [
[
'key' => '_elabel_annata',
'value' => $year,
],
],
] );
return $vintages[0] ?? null;
}
/**
* Get all published vintage posts for a product, sorted by year.
*
* @param int $product_id Product post ID.
* @param string $order Sort order ('ASC' or 'DESC').
* @return WP_Post[]
*/
function wleu_get_vintages( $product_id, $order = 'ASC' ) {
return get_posts( [
'post_type' => 'elabel_vintage',
'post_parent' => $product_id,
'posts_per_page' => -1,
'post_status' => 'publish',
'orderby' => 'meta_value',
'meta_key' => '_elabel_annata',
'order' => $order,
] );
}
// ── Activation / Deactivation ────────────────────────────────
/**
* Plugin activation.
*/
register_activation_hook( __FILE__, function () {
// Register CPT before flushing.
register_post_type( 'elabel_vintage', [
'public' => false,
'show_ui' => true,
'show_in_menu' => false,
'supports' => false,
'has_archive' => false,
'rewrite' => false,
] );
add_rewrite_rule(
'^([^/]+)-winelabel-(\d{2})/?$',
'index.php?elabel_product=$matches[1]&elabel_year=$matches[2]',
'top'
);
add_rewrite_rule(
'^([^/]+)-winelabel/?$',
'index.php?elabel_product=$matches[1]',
'top'
);
$index_slug = get_option( 'wleu_index_slug', 'winelabel' );
add_rewrite_rule(
'^' . preg_quote( $index_slug, '/' ) . '/?$',
'index.php?elabel_index=1',
'top'
);
flush_rewrite_rules();
// Store version.
update_option( 'wleu_version', WLEU_VERSION );
// Create temp dir for DomPDF.
$upload_dir = wp_upload_dir();
$tmp_dir = $upload_dir['basedir'] . '/winelabel-eu-tmp';
wp_mkdir_p( $tmp_dir );
} );
/**
* Plugin deactivation.
*/
register_deactivation_hook( __FILE__, function () {
flush_rewrite_rules();
// Clean transients only (preserve data).
delete_transient( 'wleu_license_status' );
} );