-
Notifications
You must be signed in to change notification settings - Fork 324
Expand file tree
/
Copy pathSearchOrdering.php
More file actions
863 lines (722 loc) · 28.4 KB
/
Copy pathSearchOrdering.php
File metadata and controls
863 lines (722 loc) · 28.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
<?php
/**
* Search Ordering Feature
*
* @package elasticpress
*/
namespace ElasticPress\Feature\SearchOrdering;
use ElasticPress\Feature;
use ElasticPress\FeatureRequirementsStatus;
use ElasticPress\Features;
use ElasticPress\Indexables;
use ElasticPress\REST;
use ElasticPress\Utils;
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* Search Ordering Feature
*
* @package ElasticPress\Feature\SearchOrdering
*/
class SearchOrdering extends Feature {
/**
* Internal name of the post type
*/
const POST_TYPE_NAME = 'ep-pointer';
/**
* Internal name of the taxonomy
*/
const TAXONOMY_NAME = 'ep_custom_result';
/**
* Capability required to manage.
*
* This will be removed in future versions of ElasticPress. Please use `Utils\get_capability()` instead.
*
* @deprecated 4.5.0
*/
const CAPABILITY = 'elasticpress_manage';
/**
* Initialize feature setting it's config
*
* @since 3.0
*/
public function __construct() {
$this->slug = 'searchordering';
$this->group = 'core-search';
$this->requires_install_reindex = false;
$this->requires_feature = 'search';
parent::__construct();
}
/**
* Sets i18n strings.
*
* @return void
* @since 5.2.0
*/
public function set_i18n_strings(): void {
$this->title = esc_html__( 'Custom Search Results', 'elasticpress' );
$this->summary = '<p>' . __( 'Selected posts will be inserted into search results in the specified position.', 'elasticpress' ) . '</p>';
$this->docs_url = __( 'https://www.elasticpress.io/documentation/article/configuring-elasticpress-via-the-plugin-dashboard/#custom-search-results', 'elasticpress' );
}
/**
* Setup Feature Functionality
*/
public function setup() {
/** Features Class @var Features $features */
$features = Features::factory();
/** Search Feature @var Feature\Search\Search $search */
$search = $features->get_registered_feature( 'search' );
if ( ! Utils\is_site_indexable() ) {
return false;
}
if ( ( ! $search->is_active() && $this->is_active() ) ) {
$features->deactivate_feature( $this->slug );
return false;
}
add_action( 'admin_menu', [ $this, 'admin_menu' ], 50 );
add_filter( 'parent_file', [ $this, 'parent_file' ], 50 );
add_filter( 'submenu_file', [ $this, 'submenu_file' ], 50 );
add_action( 'init', [ $this, 'register_post_type' ] );
add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] );
add_action( 'save_post_' . self::POST_TYPE_NAME, [ $this, 'save_post' ], 10, 2 );
add_action( 'posts_results', [ $this, 'posts_results' ], 20, 2 ); // Runs after core ES is done
add_action( 'rest_api_init', [ $this, 'rest_api_init' ] );
add_filter( 'ep_sync_taxonomies', [ $this, 'filter_sync_taxonomies' ] );
add_filter( 'ep_weighting_fields_for_post_type', [ $this, 'weighting_fields_for_post_type' ], 1, 2 );
add_filter( 'ep_weighting_configuration_for_search', [ $this, 'filter_weighting_configuration' ], 10, 2 );
add_filter( 'ep_weighting_configuration_for_autosuggest', [ $this, 'filter_weighting_configuration' ], 10, 1 );
add_filter( 'ep_weighting_configuration_defaults_for_autosuggest', [ $this, 'filter_weighting_configuration' ], 10, 1 );
add_filter( 'ep_weighting_default_post_type_weights', [ $this, 'filter_default_post_type_weights' ], 10, 2 );
add_filter( 'enter_title_here', [ $this, 'filter_enter_title_here' ] );
add_filter( 'manage_' . self::POST_TYPE_NAME . '_posts_columns', [ $this, 'filter_column_names' ] );
add_filter( 'post_updated_messages', [ $this, 'filter_updated_messages' ] );
add_filter( 'admin_title', [ $this, 'update_page_title' ], 10, 2 );
// Deals with trashing/untrashing/deleting
add_action( 'wp_trash_post', [ $this, 'handle_post_trash' ] );
add_action( 'before_delete_post', [ $this, 'handle_post_trash' ] );
add_action( 'untrashed_post', [ $this, 'handle_post_untrash' ] );
add_filter( 'post_row_actions', [ $this, 'remove_quick_edit' ], 10, 2 );
add_filter( 'bulk_actions-edit-' . self::POST_TYPE_NAME, [ $this, 'remove_bulk_edit' ] );
}
/**
* Remove bulk edit
*
* @param array $actions Bulk actions
* @since 3.5
* @return array
*/
public function remove_bulk_edit( $actions ) {
unset( $actions['edit'] );
return $actions;
}
/**
* Remove quick edit for post type
*
* @param array $actions Current table row actions
* @param WP_Post $post Current post
* @since 3.5
* @return array
*/
public function remove_quick_edit( $actions, $post ) {
if ( self::POST_TYPE_NAME === $post->post_type ) {
// Remove "Quick Edit"
unset( $actions['inline hide-if-no-js'] );
}
return $actions;
}
/**
* Add updated messages for post type
*
* @param array $messages Messages array
* @since 3.2
* @return array
*/
public function filter_updated_messages( $messages ) {
$post = get_post();
$post_type = get_post_type( $post );
$post_type_object = get_post_type_object( $post_type );
$messages[ self::POST_TYPE_NAME ] = array(
0 => '',
1 => esc_html__( 'Custom result updated.', 'elasticpress' ),
2 => esc_html__( 'Custom field updated.', 'elasticpress' ),
3 => esc_html__( 'Custom field deleted.', 'elasticpress' ),
4 => esc_html__( 'Custom result updated.', 'elasticpress' ),
/* translators: %s: date and time of the revision */
5 => isset( $_GET['revision'] ) ? sprintf( __( 'Custom result restored to revision from %s', 'elasticpress' ), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false, // phpcs:ignore WordPress.Security.NonceVerification
6 => esc_html__( 'Custom result published.', 'elasticpress' ),
7 => esc_html__( 'Custom result saved.', 'elasticpress' ),
8 => esc_html__( 'Custom result submitted.', 'elasticpress' ),
9 => sprintf(
// translators: Scheduled date.
esc_html__( 'Custom result scheduled for: %1$s.', 'elasticpress' ),
// translators: Publish box date format, see https://php.net/date
date_i18n( esc_html__( 'M j, Y @ G:i', 'elasticpress' ), strtotime( $post->post_date ) )
),
10 => esc_html__( 'Custom result draft updated.', 'elasticpress' ),
);
return $messages;
}
/**
* Returns requirements status of feature
*
* Requires the search feature to be activated
*
* @return FeatureRequirementsStatus
*/
public function requirements_status(): FeatureRequirementsStatus {
return new FeatureRequirementsStatus( 0, null, $this );
}
/**
* Adds this taxonomy as one of the taxonomies to index
*
* @param array $taxonomies Current indexable taxonomies
*
* @return array
*/
public function filter_sync_taxonomies( $taxonomies ) {
$taxonomies[ self::TAXONOMY_NAME ] = get_taxonomy( self::TAXONOMY_NAME );
return $taxonomies;
}
/**
* Adds the search ordering to the admin menu
*/
public function admin_menu() {
add_submenu_page(
'elasticpress',
esc_html__( 'Custom Results', 'elasticpress' ),
esc_html__( 'Custom Results', 'elasticpress' ),
Utils\get_capability( 'search-ordering' ),
'edit.php?post_type=' . self::POST_TYPE_NAME
);
}
/**
* Sets the parent menu item for the post type submenu
*
* @param string $parent_file Current parent menu item
*
* @return string
*/
public function parent_file( $parent_file ) {
global $current_screen;
if ( defined( 'EP_IS_NETWORK' ) && EP_IS_NETWORK ) {
return $parent_file;
}
// Set correct active/current menu and submenu in the WordPress Admin menu for the "pointer" CPT Add-New/Edit/List
if ( self::POST_TYPE_NAME === $current_screen->post_type ) {
$parent_file = 'elasticpress';
}
return $parent_file;
}
/**
* Ensures the correct item is highlighted when adding a new post
*
* @param string $submenu_file Current parent menu item
*
* @return string
*/
public function submenu_file( $submenu_file ) {
global $current_screen;
if ( defined( 'EP_IS_NETWORK' ) && EP_IS_NETWORK ) {
return $submenu_file;
}
// Set correct active/current menu and submenu in the WordPress Admin menu for the "pointer" CPT Add-New/Edit/List
if ( self::POST_TYPE_NAME === $current_screen->post_type ) {
$submenu_file = 'edit.php?post_type=' . self::POST_TYPE_NAME;
}
return $submenu_file;
}
/**
* Registers the pointer post type for the injected results
*/
public function register_post_type() {
$labels = array(
'name' => esc_html_x( 'Custom Search Results', 'post type general name', 'elasticpress' ),
'singular_name' => esc_html_x( 'Custom Search Result', 'post type singular name', 'elasticpress' ),
'menu_name' => esc_html_x( 'Custom Search Results', 'admin menu', 'elasticpress' ),
'name_admin_bar' => esc_html_x( 'Custom Search Result', 'add new on admin bar', 'elasticpress' ),
'add_new' => esc_html_x( 'Add New', 'book', 'elasticpress' ),
'add_new_item' => esc_html__( 'Add New Custom Search Result', 'elasticpress' ),
'new_item' => esc_html__( 'New Custom Search Result', 'elasticpress' ),
'edit_item' => esc_html__( 'Edit Custom Search Result', 'elasticpress' ),
'view_item' => esc_html__( 'View Custom Search Result', 'elasticpress' ),
'all_items' => esc_html__( 'All Custom Search Results', 'elasticpress' ),
'search_items' => esc_html__( 'Search Custom Search Results', 'elasticpress' ),
'parent_item_colon' => esc_html__( 'Parent Custom Search Result:', 'elasticpress' ),
'not_found' => esc_html__( 'No results found.', 'elasticpress' ),
'not_found_in_trash' => esc_html__( 'No results found in Trash.', 'elasticpress' ),
);
$args = array(
'labels' => $labels,
'description' => esc_html__( 'Posts to inject into search results', 'elasticpress' ),
'public' => false,
'publicly_queryable' => false,
'show_ui' => true,
'show_in_menu' => false,
'query_var' => true,
'rewrite' => array( 'slug' => 'ep-pointer' ),
'capabilities' => Utils\get_post_map_capabilities( 'search-ordering' ),
'has_archive' => false,
'hierarchical' => false,
'menu_position' => 100,
'supports' => [ 'title' ],
'register_meta_box_cb' => [ $this, 'register_meta_box' ],
'menu_icon' => 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IiB2aWV3Qm94PSIwIDAgNzMgNzEuMyIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNzMgNzEuMzsiIHhtbDpzcGFjZT0icHJlc2VydmUiPjxwYXRoIGQ9Ik0zNi41LDQuN0MxOS40LDQuNyw1LjYsMTguNiw1LjYsMzUuN2MwLDEwLDQuNywxOC45LDEyLjEsMjQuNWw0LjUtNC41YzAuMS0wLjEsMC4xLTAuMiwwLjItMC4zbDAuNy0wLjdsNi40LTYuNGMyLjEsMS4yLDQuNSwxLjksNy4xLDEuOWM4LDAsMTQuNS02LjUsMTQuNS0xNC41cy02LjUtMTQuNS0xNC41LTE0LjVTMjIsMjcuNiwyMiwzNS42YzAsMi44LDAuOCw1LjMsMi4xLDcuNWwtNi40LDYuNGMtMi45LTMuOS00LjYtOC43LTQuNi0xMy45YzAtMTIuOSwxMC41LTIzLjQsMjMuNC0yMy40czIzLjQsMTAuNSwyMy40LDIzLjRTNDkuNCw1OSwzNi41LDU5Yy0yLjEsMC00LjEtMC4zLTYtMC44bC0wLjYsMC42bC01LjIsNS40YzMuNiwxLjUsNy42LDIuMywxMS44LDIuM2MxNy4xLDAsMzAuOS0xMy45LDMwLjktMzAuOVM1My42LDQuNywzNi41LDQuN3oiIGZpbGw9IiNhN2FhYWQiLz48L3N2Zz4=',
);
register_post_type( self::POST_TYPE_NAME, $args );
// Register taxonomy
$labels = array(
'name' => esc_html_x( 'Custom Results', 'taxonomy general name', 'elasticpress' ),
'singular_name' => esc_html_x( 'Custom Result', 'taxonomy singular name', 'elasticpress' ),
'search_items' => esc_html__( 'Search Custom Results', 'elasticpress' ),
'all_items' => esc_html__( 'All Custom Results', 'elasticpress' ),
'parent_item' => esc_html__( 'Parent Custom Result', 'elasticpress' ),
'parent_item_colon' => esc_html__( 'Parent Custom Result:', 'elasticpress' ),
'edit_item' => esc_html__( 'Edit Custom Result', 'elasticpress' ),
'update_item' => esc_html__( 'Update Custom Result', 'elasticpress' ),
'add_new_item' => esc_html__( 'Add New Custom Result', 'elasticpress' ),
'new_item_name' => esc_html__( 'New Custom Result Name', 'elasticpress' ),
'menu_name' => esc_html__( 'Custom Results', 'elasticpress' ),
);
$args = array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => false,
'show_admin_column' => false,
'query_var' => false,
'rewrite' => false,
'public' => false,
);
/** Features Class @var Features $features */
$features = Features::factory();
/** Search Feature @var Feature\Search\Search $search */
$search = $features->get_registered_feature( 'search' );
$post_types = $search->get_searchable_post_types();
register_taxonomy( 'ep_custom_result', $post_types, $args );
}
/**
* Registers meta box for the search pointers
*/
public function register_meta_box() {
add_meta_box( 'ep-ordering', esc_html__( 'Manage Results', 'elasticpress' ), [ $this, 'render_meta_box' ], self::POST_TYPE_NAME, 'normal' );
}
/**
* Renders the meta box for the injected search results
*
* @param \WP_Post $post Current post object
*/
public function render_meta_box( $post ) {
?>
<div id="ordering-app"></div>
<?php
}
/**
* Sends initial pointer data to the frontend to reduce API requests required
*
* @return array
*/
public function get_pointer_data_for_localize() {
$post_id = get_the_ID();
$pointers = get_post_meta( $post_id, 'pointers', true );
if ( empty( $pointers ) ) {
return [
'pointers' => [],
'posts' => [],
'excluded_posts' => [],
];
}
$post_ids = wp_list_pluck( $pointers, 'ID' );
$query = new \WP_Query(
[
'post_type' => 'any',
'post__in' => $post_ids,
'count' => count( $post_ids ),
'orderby' => 'post__in',
]
);
$final_posts = [];
$filtered_pointers = [];
foreach ( $query->posts as $post ) {
$final_posts[ $post->ID ] = $post;
// Add the post to filtered array. By doing this, we removed the posts that don't exist anymore.
$filtered_pointers[] = $pointers[ array_search( $post->ID, $post_ids, true ) ];
}
$excluded_posts = get_post_meta( $post_id, 'excluded_posts', true );
return [
'pointers' => $filtered_pointers,
'posts' => $final_posts,
'excluded_posts' => ! empty( $excluded_posts ) ? $excluded_posts : [],
];
}
/**
* Enqueues scripts for admin interface
*/
public function admin_enqueue_scripts() {
global $pagenow; // post-new.php or post.php
$screen = get_current_screen();
if ( in_array( $pagenow, [ 'post-new.php', 'post.php' ], true ) && $screen instanceof \WP_Screen && self::POST_TYPE_NAME === $screen->post_type ) {
wp_enqueue_script(
'ep_ordering_scripts',
EP_URL . 'dist/js/ordering-script.js',
Utils\get_asset_info( 'ordering-script', 'dependencies' ),
Utils\get_asset_info( 'ordering-script', 'version' ),
true
);
wp_set_script_translations( 'ep_ordering_scripts', 'elasticpress' );
wp_enqueue_style(
'ep_ordering_styles',
EP_URL . 'dist/css/ordering-styles.css',
Utils\get_asset_info( 'ordering-styles', 'dependencies' ),
Utils\get_asset_info( 'ordering-styles', 'version' )
);
$pointer_data = $this->get_pointer_data_for_localize();
wp_localize_script(
'ep_ordering_scripts',
'epOrdering',
array_merge(
[
'searchEndpoint' => rest_url( 'elasticpress/v1/pointer_search' ),
'nonce' => wp_create_nonce( 'save-search-ordering' ),
'restApiRoot' => rest_url( '/' ),
'postsPerPage' => (int) get_option( 'posts_per_page', 10 ),
],
$pointer_data
)
);
}
}
/**
* Handles saving the injected post settings
*
* @param int $post_id Post ID of the post being saved
* @param \WP_Post $post Post object being saved
*/
public function save_post( $post_id, $post ) {
/** Post Indexable @var Post $post_indexable */
$post_indexable = Indexables::factory()->get( 'post' );
if ( ! isset( $_POST['search-ordering-nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['search-ordering-nonce'] ), 'save-search-ordering' ) ) {
return;
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
$final_order_data = [];
// Track the old IDs that aren't retained so we can delete the terms later
$previous_order_data = get_post_meta( $post_id, 'pointers', true );
$previous_post_ids = ! empty( $previous_order_data ) ? array_flip( wp_list_pluck( $previous_order_data, 'ID' ) ) : [];
$ordered_posts = isset( $_POST['ordered_posts'] ) ? wp_unslash( $_POST['ordered_posts'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$ordered_posts = json_decode( $ordered_posts, true );
$posts_per_page = (int) get_option( 'posts_per_page', 10 );
$old_search_term = get_post_meta( $post->ID, 'search_term', true );
// Search term changed, so remove it from all of the posts it was assigned to
if ( ! empty( $old_search_term ) && $old_search_term !== $post->post_title ) {
$old_term = $this->create_or_return_custom_result_term( $old_search_term, $post_id );
foreach ( array_flip( $previous_post_ids ) as $previous_post_id ) {
wp_remove_object_terms( $previous_post_id, $old_term->term_id, self::TAXONOMY_NAME );
$post_indexable->sync_manager->action_sync_on_update( $previous_post_id );
}
}
foreach ( $ordered_posts as $order_data ) {
if ( intval( $order_data['order'] ) <= $posts_per_page ) {
$final_order_data[] = [
'ID' => intval( $order_data['ID'] ),
'order' => intval( $order_data['order'] ),
'type' => ! empty( $order_data['type'] ) ? sanitize_text_field( $order_data['type'] ) : 'reordered',
];
} else {
$previous_post_ids[ intval( $order_data['ID'] ) ] = true;
}
// If the post is still assigned, no need to delete the terms later
if ( isset( $previous_post_ids[ $order_data['ID'] ] ) ) {
unset( $previous_post_ids[ $order_data['ID'] ] );
}
}
$custom_result_term = $this->create_or_return_custom_result_term( $post->post_title, $post_id );
if ( $custom_result_term ) {
foreach ( $final_order_data as $final_order_datum ) {
if ( 'publish' === $post->post_status ) {
$this->assign_term_to_post( $final_order_datum['ID'], $custom_result_term->term_taxonomy_id, $final_order_datum['order'] );
} else {
// If not published, we need to ensure that the term is _not_ present on the target posts
wp_remove_object_terms( $final_order_datum['ID'], (int) $custom_result_term->term_id, self::TAXONOMY_NAME );
}
$post_indexable->sync_manager->action_sync_on_update( $final_order_datum['ID'] );
}
}
// Remove terms for any that were deleted
if ( ! empty( $previous_post_ids ) ) {
foreach ( array_flip( $previous_post_ids ) as $old_post_id ) {
wp_remove_object_terms( $old_post_id, (int) $custom_result_term->term_id, self::TAXONOMY_NAME );
$post_indexable->sync_manager->action_sync_on_update( $old_post_id );
}
}
$excluded_posts = isset( $_POST['excluded_posts'] ) ? wp_unslash( $_POST['excluded_posts'] ) : '[]'; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$excluded_posts = json_decode( $excluded_posts, true );
$excluded_posts = ! empty( $excluded_posts ) && is_array( $excluded_posts ) ? array_map( 'intval', $excluded_posts ) : [];
// If the search term changed, clear the excluded list
if ( ! empty( $old_search_term ) && $old_search_term !== $post->post_title ) {
$excluded_posts = [];
}
update_post_meta( $post_id, 'pointers', $final_order_data );
update_post_meta( $post_id, 'excluded_posts', $excluded_posts );
update_post_meta( $post_id, 'search_term', $post->post_title );
}
/**
* Creates a term in the taxonomy for tracking ordered results or returns the existing term
*
* @param string $term_name Term name to fetch or create
* @param int|null $pointer_id Optional. Pointer post ID to associate with the term.
*
* @return false|\WP_Term
*/
public function create_or_return_custom_result_term( $term_name, $pointer_id = null ) {
$term = get_term_by( 'name', $term_name, self::TAXONOMY_NAME );
if ( ! $term ) {
$term_ids = wp_insert_term( $term_name, self::TAXONOMY_NAME );
if ( is_wp_error( $term_ids ) ) {
return false;
}
$term = get_term( $term_ids['term_id'], self::TAXONOMY_NAME );
}
if ( $term && ! empty( $pointer_id ) ) {
update_term_meta( $term->term_id, 'ep_pointer_id', $pointer_id );
}
return $term;
}
/**
* Filters available fields for weighting to exclude the custom results taxonomy
*
* @param array $fields Current weightable fields
* @param string $post_type Current post type
*
* @return array Final weightable fields
*/
public function weighting_fields_for_post_type( $fields, $post_type ) {
if ( isset( $fields['taxonomies'] ) && isset( $fields['taxonomies']['children'] ) && isset( $fields['taxonomies']['children'][ 'terms.' . self::TAXONOMY_NAME . '.name' ] ) ) {
unset( $fields['taxonomies']['children'][ 'terms.' . self::TAXONOMY_NAME . '.name' ] );
}
return $fields;
}
/**
* Filters the weighting configuration to insert our weighting config when we're searching
*
* @param array $weighting_configuration Current weighting configuration
* @param array $args WP Query Args
*
* @return array Final weighting configuration
*/
public function filter_weighting_configuration( $weighting_configuration, $args = array() ) {
if ( ! isset( $args['exclude_pointers'] ) || true !== $args['exclude_pointers'] ) {
foreach ( $weighting_configuration as $post_type => $config ) {
$weighting_configuration[ $post_type ]['terms.ep_custom_result.name'] = [
'enabled' => true,
'weight' => 9999,
'fuzziness' => false,
];
}
}
return $weighting_configuration;
}
/**
* Filters default weights for server side searches
*
* @param array $post_type_defaults Current default weight settings
* @param string $post_type Post type
*
* @return array Final weight settings
*/
public function filter_default_post_type_weights( $post_type_defaults, $post_type ) {
$post_type_defaults['terms.ep_custom_result.name'] = [
'enabled' => true,
'weight' => 9999,
'fuzziness' => false,
];
return $post_type_defaults;
}
/**
* Changes the title to show "Enter Search Query" on the CPT edit screen
*
* @param string $text Current text for the input label
*
* @return string Final label
*/
public function filter_enter_title_here( $text ) {
if ( self::POST_TYPE_NAME === get_post_type() ) {
$text = esc_html__( 'Enter Search Query', 'elasticpress' );
}
return $text;
}
/**
* Filters the title column to show "Search Query"
*
* @param array $columns Current columns
*
* @return array Final Columns
*/
public function filter_column_names( $columns ) {
$columns['title'] = esc_html__( 'Search Query', 'elasticpress' );
return $columns;
}
/**
* Finds and pointer post types in the result set and replaces them with the posts to be injected in the proper positions
*
* @param array $posts Current array of post results
* @param \WP_Query $query The current query
*
* @return array Final modified posts array
*/
public function posts_results( $posts, $query ) {
if ( is_array( $posts ) && $query->is_search() ) {
$search_query = strtolower( $query->get( 's' ) );
$to_inject = array();
$pointer_id = false;
foreach ( $posts as $key => &$post ) {
if ( isset( $post->terms ) && isset( $post->terms[ self::TAXONOMY_NAME ] ) ) {
foreach ( $post->terms[ self::TAXONOMY_NAME ] as $current_term ) {
if ( strtolower( $current_term['name'] ) === $search_query ) {
$to_inject[ $current_term['term_order'] ] = $post;
if ( empty( $pointer_id ) && ! empty( $current_term['term_id'] ) ) {
$pointer_id = get_term_meta( (int) $current_term['term_id'], 'ep_pointer_id', true );
}
unset( $posts[ $key ] );
break;
}
}
}
}
// Remove the null values
$posts = array_filter( $posts );
// Sort by key so they get injected in order and remain in the proper positions
ksort( $to_inject );
if ( ! empty( $to_inject ) ) {
foreach ( $to_inject as $position => $newpost ) {
array_splice( $posts, $position - 1, 0, array( $newpost ) );
}
}
// reindex just in case we got out of order keys
$posts = array_values( $posts );
$posts = $this->filter_excluded_posts( $posts, $pointer_id );
}
return $posts;
}
/**
* Filters out posts that have been explicitly excluded from a custom search result.
*
* @param array $posts Current array of post results.
* @param int $pointer_id ID of the custom search result pointer post.
* @return array Final modified posts array.
*/
public function filter_excluded_posts( $posts, $pointer_id ) {
static $excluded_cache = array();
if ( ! isset( $excluded_cache[ $pointer_id ] ) ) {
$excluded_cache[ $pointer_id ] = array();
if ( ! empty( $pointer_id ) ) {
$excluded = get_post_meta( $pointer_id, 'excluded_posts', true );
if ( ! empty( $excluded ) && is_array( $excluded ) ) {
$excluded_cache[ $pointer_id ] = array_map( 'intval', $excluded );
}
}
}
$excluded_posts = $excluded_cache[ $pointer_id ];
if ( empty( $excluded_posts ) ) {
return $posts;
}
$posts = array_filter(
$posts,
function ( $post ) use ( $excluded_posts ) {
return ! in_array( (int) $post->ID, $excluded_posts, true );
}
);
return array_values( $posts );
}
/**
* Registers the API endpoint for searching from the admin interface
*/
public function rest_api_init() {
$controller = new REST\SearchOrdering();
$controller->register_routes();
}
/**
* Removes taxonomy terms from the references posts when a pointer is deleted or trashed
*
* @param int $post_id Post ID that is being deleted
*/
public function handle_post_trash( $post_id ) {
$post = get_post( $post_id );
if ( self::POST_TYPE_NAME !== $post->post_type ) {
return;
}
/** Post Indexable @var Post $post_indexable */
$post_indexable = Indexables::factory()->get( 'post' );
$pointers = get_post_meta( $post_id, 'pointers', true );
$term = $this->create_or_return_custom_result_term( $post->post_title );
if ( empty( $pointers ) ) {
return;
}
foreach ( $pointers as $pointer ) {
$ref_id = $pointer['ID'];
wp_remove_object_terms( $ref_id, (int) $term->term_id, self::TAXONOMY_NAME );
$post_indexable->sync_manager->action_sync_on_update( $ref_id );
}
}
/**
* Handles reassigning terms to the posts when a pointer post is restored from trash
*
* @param int $post_id Post ID
*/
public function handle_post_untrash( $post_id ) {
$post = get_post( $post_id );
if ( self::POST_TYPE_NAME !== $post->post_type ) {
return;
}
/** Post Indexable @var Post $post_indexable */
$post_indexable = Indexables::factory()->get( 'post' );
$pointers = get_post_meta( $post_id, 'pointers', true );
$term = $this->create_or_return_custom_result_term( $post->post_title );
if ( 'publish' === $post->post_status ) {
foreach ( $pointers as $pointer ) {
$this->assign_term_to_post( $pointer['ID'], $term->term_taxonomy_id, $pointer['order'] );
$post_indexable->sync_manager->action_sync_on_update( $pointer['ID'] );
}
}
}
/**
* Assigns the term to the post with the proper term_order value
*
* @param int $post_id The Post ID
* @param int $term_taxonomy_id Term Taxonomy ID
* @param int $order Term order to assign
*
* @return bool|int
*/
protected function assign_term_to_post( $post_id, $term_taxonomy_id, $order ) {
global $wpdb;
$result = $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->prepare(
"INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES ( %d, %d, %d ) ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)",
$post_id,
$term_taxonomy_id,
$order
)
);
// Delete the term order cache
wp_cache_delete( "{$post_id}_term_order" );
// Clears the core cache
wp_cache_delete( $post_id, self::TAXONOMY_NAME . '_relationships' );
return $result;
}
/**
* Update the page title to keep the consistency through the plugin
*
* @param string $admin_title The page title, with extra context added
* @param string $title The original page title
*
* @return string Updated the page title
*/
public function update_page_title( $admin_title, $title ) {
if ( $this->title === $title ) {
return __( 'ElasticPress Custom Search Results', 'elasticpress' );
}
return $admin_title;
}
}