Post.php
44.6 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
<?php
/**
* SearchWP Posts Source.
*
* @package SearchWP
* @author Jon Christopher
*/
namespace SearchWP\Sources;
use SearchWP\Utils;
use SearchWP\Entry;
use SearchWP\Query;
use SearchWP\Source;
use SearchWP\Option;
use SearchWP\Notice;
use SearchWP\Settings;
use SearchWP\Highlighter;
/**
* Class Post is a Source for WP_Post objects.
*
* @since 4.0
*/
class Post extends Source {
/**
* The post type name.
*
* @since 4.0
* @package SearchWP\Sources
* @var string
*/
private $post_type;
/**
* Column name used to track index status.
*
* @since 4.0
* @var string
*/
protected $db_id_column = 'ID';
/**
* Column used for post parent ID.
*
* @since 4.1
* @var string
*/
protected $db_post_parent_column = 'post_parent';
/**
* Constructor.
*
* @since 4.0
*/
function __construct( string $post_type = 'post' ) {
global $wpdb, $wp_query;
$post_type_model = get_post_type_object( $post_type );
if ( is_null( $post_type_model ) && ( isset( $wp_query ) && is_search() ) ) {
wp_die(
__( 'Invalid post type for SearchWP Source Post:', 'searchwp' ) . ' <code>' . esc_html( $post_type ) . '</code>',
__( 'SearchWP Source Error', 'searchwp' )
);
}
if ( ! $post_type_model instanceof \WP_Post_type ) {
do_action( 'searchwp\debug\log', "Invalid post type for SearchWP Source Post:", 'source' );
do_action( 'searchwp\debug\log', print_r( $post_type, true ), 'source' );
if ( current_user_can( \SearchWP\Settings::get_capability() ) ) {
wp_die(
__( 'Invalid post type for SearchWP Source Post:', 'searchwp' ) . ' <code>' . esc_html( $post_type ) . '</code>',
__( 'SearchWP Source Error', 'searchwp' )
);
}
} else {
$this->labels = [
'plural' => $post_type_model->labels->name,
'singular' => $post_type_model->labels->singular_name,
];
}
$this->name = 'post' . SEARCHWP_SEPARATOR . $post_type;
$this->post_type = $post_type;
$this->db_table = $this->db_table . $wpdb->posts;
$this->attributes = $this->attributes();
$this->rules = $this->rules();
}
/**
* Gets permalink for Source Entry ID.
*
* @since 4.1.14
* @param int $id ID of the Entry
* @return null|string
*/
public static function get_permalink( int $post_id ) {
return get_permalink( $post_id );
}
/**
* Gets edit link for Source Entry ID.
*
* @since 4.1.14
* @param int $id ID of the Entry
* @return null|string
*/
public static function get_edit_link( int $id ) {
return get_edit_post_link( $id, '' ); // Pass empty context to prevent urlencode.
}
/**
* Adds notice when this post type is intended to be excluded from search.
*
* @since 4.0
* @param Notice[] Existing notices
* @return Notice[]
*/
protected function notices( $notices ) {
if ( $this->is_excluded_from_search() ) {
$notices[] = new Notice( '', [
'tooltip' => sprintf(
// Translators: %s is the plural label of a post type.
__( 'Note: by default %s are set to be excluded from search. Enabling %s overrides this.', 'searchwp' ),
$this->labels['plural'],
$this->labels['plural']
),
] );
}
return $notices;
}
/**
* Whether this post types was intended to be excluded from search.
*
* @since 4.0
* @return bool
*/
public function is_excluded_from_search() {
$post_type = get_post_type_object( $this->post_type );
return ! is_null( $post_type ) ? $post_type->exclude_from_search : true;
}
/**
* Restrict available Posts to this post type with the proper post stati and exclusions.
*
* @since 4.0
* @return array
*/
protected function db_where() {
$args = [
'post_type' => $this->post_type,
'source' => $this,
];
return apply_filters( 'searchwp\source\post\db_where', [
'relation' => 'AND',
[ // Only include applicable post type.
'column' => 'post_type',
'value' => $this->post_type,
],
[ // Only include applicable post stati.
'column' => 'post_status',
'value' => Utils::get_post_type_stati( $this->post_type ),
'compare' => 'IN',
],
[ // ID-based limiter.
'column' => 'ID',
'value' => Utils::get_filtered_post__in( $args ),
'compare' => 'IN',
'type' => 'NUMERIC',
],
[ // ID-based exclusions.
'column' => 'ID',
'value' => Utils::get_filtered_post__not_in( $args ),
'compare' => 'NOT IN',
'type' => 'NUMERIC',
],
], $args );
}
/**
* Defines the Attributes for this Source.
*
* @since 4.0
* @return array
*/
protected function attributes() {
global $wpdb;
$attributes = [
[ // Title.
'name' => 'title',
'label' => __( 'Title', 'searchwp' ),
'default' => $this->is_excluded_from_search() ? false : Utils::get_max_engine_weight(),
'data' => function( $post_id ) {
return get_the_title( $post_id );
},
'phrases' => 'post_title',
],
[ // Post content.
'name' => 'content',
'label' => __( 'Content', 'searchwp' ),
'default' => $this->is_excluded_from_search() ? false : Utils::get_min_engine_weight(),
'data' => function( $post_id ) {
$post = get_post( $post_id );
$content = ! is_null( $post ) ? $post->post_content : '';
$do_shortcodes = apply_filters(
'searchwp\source\post\attributes\content\do_shortcodes',
Settings::get_single( 'parse_shortcodes', 'boolean' ),
[ 'post' => $post, ]
);
$do_blocks = function_exists( 'has_blocks' )
&& function_exists( 'do_blocks' )
&& apply_filters( 'searchwp\source\post\attributes\content\do_blocks', true, [
'post' => $post,
] );
if ( $do_shortcodes && $do_blocks ) {
$content = apply_filters( 'the_content', $content );
} else if ( ! $do_shortcodes && $do_blocks && has_blocks( $content ) ) {
$content = do_blocks( $content );
} else if ( $do_shortcodes && ! $do_blocks ) {
$content = do_shortcode( $content );
}
return apply_filters( 'searchwp\source\post\attributes\content', $content, [
'post' => $post,
] );
},
'phrases' => 'post_content',
],
[ // Post slug.
'name' => 'slug',
'label' => __( 'Slug', 'searchwp' ),
'default' => $this->is_excluded_from_search() ? false : Utils::get_max_engine_weight(),
'data' => function( $post_id ) {
$slug = get_post_field( 'post_name', get_post( $post_id ) );
// By default regex pattern matches are exclusive, but in this case we want
// to index the parts of the slug because they're an exception to the rule.
if ( ! apply_filters( 'searchwp\source\post\attributes\slug\strict', false ) ) {
$slug = str_replace( [ '-', '_' ], ' ', $slug );
}
return $slug;
},
],
[ // Post excerpt.
'name' => 'excerpt',
'label' => __( 'Excerpt', 'searchwp' ),
'default' => $this->is_excluded_from_search() ? false : Utils::get_min_engine_weight(),
'data' => function( $post_id ) {
return get_the_excerpt( $post_id );
},
'phrases' => 'post_excerpt',
],
[ // Custom Fields.
'name' => 'meta',
'label' => __( 'Custom Fields', 'searchwp' ),
'notes' => [
__( 'Tip: Match multiple keys using * as wildcard and hitting Enter', 'searchwp' ),
],
'default' => $this->is_excluded_from_search() ? false : Utils::get_min_engine_weight(),
'options' => function( $search = false, array $include = [] ) {
// If we're retrieving a specific set of options, get them and return.
if ( ! empty( $include ) ) {
return array_map( function( $meta_key ) {
return new Option( (string) $meta_key );
}, $include );
}
return array_map( function( $meta_key ) {
return new Option( $meta_key );
}, Utils::get_meta_keys_for_post_type( $this->post_type, $search ) );
},
'allow_custom' => true,
'data' => function( $post_id, $meta_key ) {
// Because partial matching is supported, we're going to work with an array of meta keys even if it's one.
if ( false !== strpos( '*', $meta_key ) ) {
$meta_keys = Utils::get_meta_keys_for_post_type( $this->post_type, $meta_key );
} else {
$meta_keys = [ $meta_key ];
}
$do_shortcodes = apply_filters(
'searchwp\source\post\attributes\content\do_shortcodes',
Settings::get_single( 'parse_shortcodes', 'boolean' ),
[ 'post' => $post_id, ]
);
$meta_value = array_filter( array_map( function( $meta_key ) use ( $post_id, $do_shortcodes ) {
$post_meta = get_post_meta( $post_id, $meta_key, false );
// If there was only one record, let's clean it up.
if ( is_array( $post_meta ) && 1 === count( $post_meta ) ) {
$post_meta = array_values( $post_meta );
$post_meta = array_shift( $post_meta );
}
if ( $do_shortcodes ) {
if ( is_array( $post_meta ) ) {
// Support string[] but anything more advanced can use a hook.
$post_meta = array_map( function( $this_meta ) {
if ( is_string( $this_meta ) ) {
return do_shortcode( $this_meta );
} else {
return $this_meta;
}
}, $post_meta );
} else {
$post_meta = do_shortcode( $post_meta );
}
}
return $post_meta;
}, $meta_keys ) );
$meta_value = apply_filters(
'searchwp\source\post\attributes\meta',
apply_filters(
'searchwp\source\post\attributes\meta\\' . $meta_key,
$meta_value,
[ 'post_id' => $post_id, ]
), [
'post_id' => $post_id,
'meta_key' => $meta_key,
'meta_value' => $meta_value,
] );
return $meta_value;
},
'phrases' => [ [
'table' => $wpdb->postmeta,
'column' => 'meta_value',
'id' => 'post_id'
] ],
],
[ // Taxonomies.
'name' => 'taxonomy',
'label' => __( 'Taxonomies', 'searchwp' ),
'default' => $this->is_excluded_from_search() ? false : Utils::get_max_engine_weight(),
'options' => function() {
return array_map( function( $taxonomy ) {
return new Option( $taxonomy->name, $taxonomy->label . ' (' . $taxonomy->name . ')' );
}, get_object_taxonomies( $this->post_type, 'objects' ) );
},
'data' => function( $post_id, $taxonomy ) {
do_action( 'searchwp\source\post\attributes\taxonomy', [
'taxonomy' => $taxonomy,
'post_id' => $post_id,
'post_type' => $this->post_type,
] );
$terms = apply_filters(
'searchwp\source\post\attributes\taxonomy\terms',
get_the_terms( $post_id, $taxonomy ), [
'taxonomy' => $taxonomy,
'post_id' => $post_id,
'post_type' => $this->post_type,
] );
if ( is_array( $terms ) && ! empty( $terms ) ) {
$terms = array_map( function( $term ) {
$term = get_term( $term ); // Allow hooks to run.
$term_array = [
'name' => $term->name,
'slug' => $term->slug,
'desc' => $term->description,
];
return apply_filters( 'searchwp\source\post\attributes\taxonomy\term', $term_array, [
'taxonomy' => $term->taxonomy,
'name' => $term->name,
'slug' => $term->slug,
'desc' => $term->description,
] );
}, $terms );
}
return $terms;
},
],
];
return $attributes;
}
/**
* Weight Transfer Option options.
*
* @since 4.0
* @return array
*/
protected function weight_transfer_options( $force_parent_attribution = false ) {
$options = [];
if ( apply_filters( 'searchwp\source\post\\' . $this->post_type . '\attribution', true ) ) {
$options[] = [
'option' => new Option( 'id', sprintf(
// Translators: placeholder is singular post type label.
__( 'To %s ID', 'searchwp' ),
$this->labels['singular']
) ),
'source_map' => function( $args ) {
global $wpdb;
$post_type = get_post_type( $args['id'] );
do_action( 'searchwp\debug\log', "Transferring {$this->get_name()} weight to {$post_type}:{$args['id']}", 'source' );
return $wpdb->prepare( '%s', 'post' . SEARCHWP_SEPARATOR . $post_type );
}
];
}
// TODO: this reference to Attachment should be handled by the Attachment Source.
$enable_parent_attribution = is_post_type_hierarchical( $this->post_type ) || 'attachment' === $this->post_type;
if ( $force_parent_attribution || apply_filters(
'searchwp\source\post\\' . $this->post_type . '\parent_attribution',
$enable_parent_attribution
) ) {
$option = [
'option' => new Option( 'col', sprintf(
// Translators: placeholder is singular post type label.
__( 'To %s Parent', 'searchwp' ),
$this->labels['singular']
) ),
'value' => $this->db_post_parent_column, // Just the column name, an alias is created for this Source's table.
'conditions' => function( $args ) {
// TODO: This checks only post stati, should it be more comprehensive and check db_where?
if ( ! apply_filters(
'searchwp\source\post\\' . $this->post_type . '\parent_attribution\check_post_stati',
true
) ) {
return '';
}
do_action( 'searchwp\debug\log', "Transferring {$this->post_type} weight to {$this->db_post_parent_column}", 'source' );
return [
'id' => $this->get_post_parent_id_case_sql( $args ),
'source' => $this->get_post_parent_source_case_sql( $args ),
];
}
];
// If attribution is strict, entries without a post_parent will be dropped from the results set.
// If attribution is not strict, child entries will be returned as a fallback.
if ( ! apply_filters( 'searchwp\source\post\\' . $this->post_type . '\parent_attribution\strict', false ) ) {
$option[ 'fallback' ] = [ '0' ]; // Entries with a post_parent of zero have no parent.
}
$options[] = $option;
}
return $options;
}
/**
* Generates the SQL necessary for the s.id clause for post parent weight transfer.
*
* @since 4.1
* @param array $args The incoming arguments.
* @param string $db_table The name of the database table.
* @param string $db_post_parent_column The name of the column that stores the parent ID.
* @param string[] $potential_parents The potential parent post types.
* @param bool $strict Whether results should be strict i.e. only contain added Engine Sources as opposed to any Source.
* @return string SQL
*/
public function get_post_parent_source_case_sql( $args, $db_table = '', $db_post_parent_column = '', $potential_parents = [], $strict = true ) {
global $wpdb;
if ( empty( $db_table ) ) {
$db_table = $this->db_table;
}
if ( empty( $db_post_parent_column ) ) {
$db_post_parent_column = $this->db_post_parent_column;
}
if ( empty( $potential_parents ) ) {
$potential_parents = $this->get_potential_post_parent_types( $args );
}
// If we're not strict then we're always going to return the parent post type.
if ( ! $strict ) {
return $wpdb->prepare(
"CONCAT( %s,
( SELECT post_type
FROM {$wpdb->posts}
WHERE {$wpdb->posts}.ID = {$args['alias']}.{$db_post_parent_column} )
)",
'post' . SEARCHWP_SEPARATOR
);
}
// CASE each applicable post type with appropriate post stati.
$conditions = array_map( function( $post_type ) use ( $args, $db_table, $db_post_parent_column ) {
global $wpdb;
$post_type_stati = array_map( function( $status ) use ( $wpdb ) {
return $wpdb->prepare( '%s', $status );
}, Utils::get_post_type_stati( $post_type ) );
return 'WHEN ' . $wpdb->prepare( '%s', $post_type ) . " = (
SELECT post_type
FROM {$db_table}
WHERE {$db_table}.ID = {$args['alias']}.{$db_post_parent_column}
) AND (
SELECT post_status
FROM {$db_table}
WHERE {$db_table}.ID = {$args['alias']}.{$db_post_parent_column}
) IN (" .
implode( ', ', $post_type_stati ) . ') THEN ' . $wpdb->prepare( '%s', 'post' . SEARCHWP_SEPARATOR . $post_type );
}, $potential_parents );
return 'CASE ' . implode( ' ', $conditions ) . " ELSE {$args['index_alias']}.source END";
}
/**
* Generates the SQL necessary for the s.source clause for post parent weight transfer.
*
* @since 4.1
* @param array $args The incoming arguments.
* @param string $db_table The name of the database table.
* @param string $db_post_parent_column The name of the column that stores the parent ID.
* @param string[] $potential_parents The potential parent post types.
* @param bool $strict Whether results should be strict i.e. only contain added Engine Sources as opposed to any Source.
* @return string SQL
*/
public function get_post_parent_id_case_sql( $args, $db_table = '', $db_post_parent_column = '', $potential_parents = [], $strict = true ) {
if ( empty( $db_table ) ) {
$db_table = $this->db_table;
}
if ( empty( $db_post_parent_column ) ) {
$db_post_parent_column = $this->db_post_parent_column;
}
if ( empty( $potential_parents ) ) {
$potential_parents = $this->get_potential_post_parent_types( $args );
}
// If we're not strict then we're always going to return the actual Source ID.
if ( ! $strict ) {
return "{$args['alias']}.{$db_post_parent_column}";
}
// CASE each applicable post type with appropriate post stati.
$conditions = array_map( function( $post_type ) use ( $args, $db_table, $db_post_parent_column ) {
global $wpdb;
$post_type_stati = array_map( function( $status ) use ( $wpdb ) {
return $wpdb->prepare( '%s', $status );
}, Utils::get_post_type_stati( $post_type ) );
return $wpdb->prepare( '%s', $post_type ) . " = (
SELECT post_type
FROM {$db_table}
WHERE {$db_table}.ID = {$args['alias']}.{$db_post_parent_column}
) AND (
SELECT post_status
FROM {$db_table}
WHERE {$db_table}.ID = {$args['alias']}.{$db_post_parent_column}
) IN (" .
implode( ', ', $post_type_stati ) . ')';
}, $potential_parents );
return 'CASE WHEN ' . implode( ' OR ', $conditions ) . " THEN {$args['alias']}.{$db_post_parent_column} ELSE 0 END";
}
/**
* Retrieves all potential parent post types from the current Engine.
*
* @since 4.1
* @param array $args The arguments for the weight transfer option.
* @return string[] Post type names.
*/
public function get_potential_post_parent_types( $args, $child_post_type = '' ) {
if ( empty( $child_post_type ) ) {
$child_post_type = $this->get_post_type();
}
// We need to ensure that parent post type is taken into consideration when attribution applies.
// Unfortunately this means we need to iterate over all post types because they each have uniuqe stati.
$flag = 'post' . SEARCHWP_SEPARATOR;
// Get a list of applicable post type names (WP_Post-based and not $this->post_type).
return array_map( function( $source_name ) use ( $flag ) {
return substr( $source_name, strlen( $flag ) );
}, array_filter(
array_keys( $args['query']->get_engine()->get_sources() ),
function( $source_name ) use ( $flag, $child_post_type ) {
// Parents need to be a WP_Post but can be the same post type e.g. Pages.
return $flag === substr( $source_name, 0, strlen( $flag ) );
}
) );
}
/**
* Returns a baseline set of WP_Query arguments.
*
* @since 4.0
* @return (string|array|true)[]
*/
protected function get_base_wp_query_args() {
return [
'post_type' => $this->post_type,
'post_status' => Utils::get_post_type_stati( $this->post_type ),
'post__in' => Utils::get_filtered_post__in(),
'post__not_in' => Utils::get_filtered_post__not_in(),
'orderby' => 'none',
'fields' => 'ids',
'nopaging' => true,
'suppress_filters' => true,
];
}
/**
* Defines the Rules for this Source.
*
* @since 4.0
* @return array
*/
protected function rules() {
$base_wp_query_args = $this->get_base_wp_query_args();
$rules = [
[ // Taxonomies.
'name' => 'taxonomy',
'label' => __( 'Taxonomy', 'searchwp' ),
'options' => function() {
// The Options for this Rule are Taxonomy names.
return array_map( function( $taxonomy ) {
return new Option( $taxonomy->name, $taxonomy->label . ' (' . $taxonomy->name . ')' );
}, get_object_taxonomies( $this->post_type, 'objects' ) );
},
'conditions' => [ 'IN', 'NOT IN' ],
'values' => function( $option, $search = false, array $include = [] ) {
$args = [
'taxonomy' => $option,
'hide_empty' => false,
];
if ( $search ) {
$args['name__like'] = $search;
}
if ( count( $include ) ) {
$args['include'] = $include;
}
// The Conditions for each Option of this Rule are Taxonomy Terms.
return array_map( function( $term ) {
return new Option( $term->term_id, $term->name );
}, get_terms( $args ) );
},
'application' => function( $properties ) use ( $base_wp_query_args ) {
$tax_rule_wp_query = new \WP_Query( array_merge( [
'tax_query' => [ [
'taxonomy' => $properties['option'],
'field' => 'term_id',
'terms' => $properties['value'],
'operator' => $properties['condition'],
] ],
], $base_wp_query_args ) );
// Return the IDs we already did the work to find if there aren't too many.
if ( empty( $tax_rule_wp_query->posts ) ) {
return [ 0 ];
} else if ( $tax_rule_wp_query->found_posts < 20 ) {
return $tax_rule_wp_query->posts;
} else {
return $tax_rule_wp_query->request;
}
}
],
[ // Publish date.
'name' => 'published',
'label' => __( 'Publish Date', 'searchwp' ),
'tooltip' => __( 'Any strtotime()-compatible string e.g. "6 months ago"', 'searchwp' ),
'options' => false,
'conditions' => [ '<', '>' ],
'application' => function( $properties ) use ( $base_wp_query_args ) {
$condition = $properties['condition'] === '<' ? 'before' : 'after';
$date_query = [ 'inclusive' => false ];
$date_query[ $condition ] = $properties['value'];
$published_rule_wp_query = new \WP_Query( array_merge( [
'date_query' => [ $date_query ],
], $base_wp_query_args ) );
// Return the IDs we already did the work to find if there aren't too many.
if ( empty( $published_rule_wp_query->posts ) ) {
return [ 0 ];
} else if ( $published_rule_wp_query->found_posts < 20 ) {
return $published_rule_wp_query->posts;
} else {
return $published_rule_wp_query->request;
}
},
],
[ // ID.
'name' => 'post_id',
'label' => __( 'ID', 'searchwp' ),
'options' => false,
'conditions' => [ 'IN', 'NOT IN' ],
'application' => function( $properties ) {
global $wpdb;
$condition = 'NOT IN' === $properties['condition'] ? 'NOT IN' : 'IN';
$ids = explode( ',', Utils::get_integer_csv_string_from( $properties['value'] ) );
return $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE ID {$condition} ("
. implode( ',', array_fill( 0, count( $ids ), '%s' ) )
. ')', $ids );
},
],
];
// Some rules apply only when the post type is hierarchical.
$post_type = get_post_type_object( $this->post_type );
if ( $post_type->hierarchical ) {
$rules = array_merge( $rules, [
[ // Ancestor.
'name' => 'ancestor',
'label' => __( 'Ancestor ID', 'searchwp' ),
'tooltip' => __( 'Ancestor and all descendants will apply to this Rule, comma separate multiple ancestors', 'searchwp' ),
'options' => false,
'conditions' => [ 'IN', 'NOT IN' ],
'application' => function( $properties ) {
global $wpdb;
$condition = 'NOT IN' === $properties['condition'] ? 'NOT IN' : 'IN';
$ancestors = explode( ',', Utils::get_integer_csv_string_from( $properties['value'] ) );
$ids = [];
foreach ( $ancestors as $ancestor ) {
$ids = array_merge( $ids, \SearchWP\Utils::get_descendant_post_parents( $ancestor ) );
}
// Force empty IDs if applicable.
if ( empty( $ids ) ) {
$ids = [ '' ];
}
return $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_parent {$condition} ("
. implode( ',', array_fill( 0, count( $ids ), '%s' ) )
. ')', $ids );
},
],
[ // Post Parent.
'name' => 'post_parent',
'label' => __( 'Post Parent ID', 'searchwp' ),
'tooltip' => __( 'Applies only to children, add another Rule to consider Post Parent itself if necessary', 'searchwp' ),
'options' => false,
'conditions' => [ 'IN', 'NOT IN' ],
'application' => function( $properties ) {
global $wpdb;
$condition = 'NOT IN' === $properties['condition'] ? 'NOT IN' : 'IN';
$ids = explode( ',', Utils::get_integer_csv_string_from( $properties['value'] ) );
// Force empty IDs if applicable.
if ( empty( $ids ) ) {
$ids = [ '' ];
}
return $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_parent {$condition} ("
. implode( ',', array_fill( 0, count( $ids ), '%s' ) )
. ')', $ids );
},
],
] );
}
return $rules;
}
/**
* Maps an Entry for this Source to its native model.
*
* @since 4.0
* @param Entry $entry The Entry
* @param Boolean $doing_query Whether a query is being run
* @return mixed
*/
public function entry( Entry $entry, $doing_query = false ) {
$post = get_post( $entry->get_id() );
if ( ! $post instanceof \WP_Post ) {
return $post;
}
// Set up highlighter if applicable.
$highlighter = Settings::get( 'highlighting', 'boolean' ) ? new Highlighter() : false;
$highlighter = apply_filters( 'searchwp\source\post\do_highlighting', $highlighter, [
'entry' => $entry,
'query' => $doing_query,
] );
// Determine whether we're going to find a global excerpt based on whether highlighting is enabled.
$global_excerpt = apply_filters( 'searchwp\source\post\global_excerpt', ! empty( $highlighter ), [ 'entry' => $entry, ] );
$global_excerpt = apply_filters( 'searchwp\source\post\global_excerpt\\' . $this->post_type, $global_excerpt, [ 'entry' => $entry, ] );
// Set the excerpt early if global excerpt is applicable.
if ( $doing_query instanceof Query && $global_excerpt ) {
$post->post_excerpt = self::get_global_excerpt( $entry, $doing_query );
}
// Apply highlights if applicable.
if ( $doing_query instanceof Query && $highlighter ) {
// Be sure to check suggested search strings and not just the submitted search.
if ( ! empty( $doing_query->get_suggested_search() ) ) {
$search_terms = $doing_query->get_suggested_search();
} else {
// We have to be careful here e.g. with synonyms. We only really want to work with
// the original, submitted search string. If we consider synonyms or any other
// modifications to the search string itself, we could get both a weird excerpt
// and further weird ancillary changes like highlighting the modifications.
// However in some cases devs may want that, so leave the option.
$search_terms = apply_filters( 'searchwp\source\post\global_excerpt\use_original_search_string', true )
? $doing_query->get_keywords( true )
: implode( ' ', array_merge( [ $doing_query->get_keywords() ], $doing_query->get_tokens() ) );
}
// If this is a quoted search, limit the highlight to the quoted search.
if ( false !== strpos( $search_terms, '"' ) ) {
$search_terms = str_replace( '"', '', $doing_query->get_keywords() );
}
$search_terms = explode( ' ', $search_terms );
$post->post_title = $highlighter::apply( get_the_title( $post ), $search_terms );
$post->post_excerpt = $highlighter::apply( $post->post_excerpt, $search_terms );
}
return $post;
}
/**
* Getter for post type.
*
* @since 4.0
* @return string
*/
public function get_post_type() {
return $this->post_type;
}
/**
* Returns a global excerpt based on the submitted WP_Post. Will check all enabled Attributes.
*
* @since 4.0
* @param Entry $entry The entry to consider.
* @param string|Query $query Either the search string or a Query proper.
* @return string An excerpt containing (at least) the first search term.
*/
public static function get_global_excerpt( Entry $entry, $query, $length = 55 ) {
do_action( 'searchwp\get_global_excerpt' );
$post_id = $entry->get_id();
$post = get_post( $post_id );
if ( ! $post instanceof \WP_Post ) {
return '';
}
if ( $query instanceof Query ) {
// Be sure to check suggested search strings and not just the submitted search.
if ( ! empty( $query->get_suggested_search() ) ) {
$search_terms = $query->get_suggested_search();
} else {
// We have to be careful here e.g. with synonyms. We only really want to work with
// the original, submitted search string. If we consider synonyms or any other
// modifications to the search string itself, we could get both a weird excerpt
// and further weird ancillary changes like highlighting the modifications.
// However in some cases devs may want that, so leave the option.
if ( ! apply_filters( 'searchwp\source\post\global_excerpt\use_original_search_string', true )
&& ! empty( array_diff( explode( ' ', str_replace( '"', '', $query->get_keywords() ) ), $query->get_tokens() ) ) )
{
$search_terms = implode( ' ', array_merge( [ $query->get_keywords() ], $query->get_tokens() ) );
} else {
$search_terms = $query->get_keywords( true );
}
}
} else {
$search_terms = (string) $query;
}
// If this is a quoted search, we should remove the quotes before proceeding
if ( false !== strpos( $search_terms, '"' ) ) {
$search_terms = str_replace( '"', '', $search_terms );
}
// Priority is the existing Excerpt.
$excerpt = isset( $post->post_excerpt ) ? $post->post_excerpt : '';
$excerpt = apply_filters( 'searchwp\source\post\excerpt_haystack', $excerpt, [
'search' => $search_terms,
'post' => $post,
'query' => $query,
] );
if ( ! empty( $excerpt ) && Utils::string_has_substring_from_string( $excerpt, $search_terms ) ) {
return Utils::trim_string_around_substring(
$excerpt,
$search_terms,
$length
);
}
// Next check the post content.
$content = Utils::stringify_html( apply_filters( 'the_content', $post->post_content ) );
if ( ! empty( $content ) ) {
$content = apply_filters( 'searchwp\source\post\excerpt_haystack', $content, [
'search' => $search_terms,
'post' => $post,
'query' => $query,
] );
if ( ! empty( $content ) && Utils::string_has_substring_from_string( $content, $search_terms ) ) {
return Utils::trim_string_around_substring(
$content,
$search_terms,
$length
);
}
}
// Facilitate a kill switch.
if ( apply_filters( 'searchwp\source\post\global_excerpt_break', false, [
'search' => $search_terms,
'post' => $post,
'query' => $query,
] ) ) {
return ! empty( $excerpt ) ? $excerpt : get_the_title( $post_id );
}
$entry_data = $entry->get_data( true, true );
// Check Document Content.
if ( isset( $entry_data['document_content'] ) && ! empty( $entry_data['document_content'] ) ) {
$content = apply_filters( 'searchwp\source\post\excerpt_haystack', $entry_data['document_content'], [
'search' => $search_terms,
'post' => $post,
'query' => $query,
] );
if ( ! empty( $content ) && Utils::string_has_substring_from_string( $content, $search_terms ) ) {
return Utils::trim_string_around_substring(
$content,
$search_terms,
$length
);
}
}
// Lastly check postmeta.
$meta_value_excerpt = false;
if ( ! empty( $entry_data['meta'] ) && is_array( $entry_data['meta'] ) ) {
foreach ( $entry_data['meta'] as $meta_key => $meta_data ) {
$meta_value = apply_filters( 'searchwp\source\post\excerpt_haystack', $meta_data, [
'search' => $search_terms,
'post' => $post,
'query' => $query,
'meta_key' => $meta_key,
] );
$meta_value = Utils::get_string_from( $meta_value );
if ( ! empty( $meta_value ) && Utils::string_has_substring_from_string( $meta_value, $search_terms ) ) {
$do_shortcodes = apply_filters(
'searchwp\source\post\attributes\content\do_shortcodes',
Settings::get_single( 'parse_shortcodes', 'boolean' ),
[ 'post' => $post, ]
);
if ( $do_shortcodes ) {
$meta_value = do_shortcode( $meta_value );
}
$meta_value = Utils::stringify_html( $meta_value );
$meta_value_excerpt = Utils::trim_string_around_substring(
$meta_value,
$search_terms,
$length
);
break;
}
}
if ( ! empty( $meta_value_excerpt ) ) {
return $meta_value_excerpt;
}
}
// Nothing was found, send back the native excerpt or worst case the title.
return ! empty( $excerpt ) ? $excerpt : apply_filters( 'searchwp\source\post\excerpt_fallback', get_the_excerpt( $post_id ), [
'search' => $search_terms,
'post' => $post,
'query' => $query,
] );
}
/**
* Add class hooks.
*
* @since 4.0
* @param array $params Parameters.
* @return array
*/
public function add_hooks( array $params = [] ) {
// Custom Fields.
if ( ! has_filter( 'searchwp\source\attribute\options', [ $this, 'special_meta_keys' ] ) ) {
add_filter( 'searchwp\source\attribute\options', [ $this, 'special_meta_keys' ], 9, 2 );
}
if ( ! has_filter( 'searchwp\source\attribute\options\special', [ $this, 'special_meta_keys' ] ) ) {
add_filter( 'searchwp\source\attribute\options\special', [ $this, 'special_meta_keys' ], 9, 2 );
}
// Output taxonomy names.
// TODO: Refactor with Issue #264.
if ( ! has_filter( 'searchwp\source\attribute\options', [ $this, 'add_taxonomy_names' ] ) ) {
add_filter( 'searchwp\source\attribute\options', [ $this, 'add_taxonomy_names' ], 5, 2 );
}
if ( ! has_filter( 'searchwp\source\attribute\options\special', [ $this, 'add_taxonomy_names' ] ) ) {
add_filter( 'searchwp\source\attribute\options\special', [ $this, 'add_taxonomy_names' ], 5, 2 );
}
// We want ACF Repeatables to be integrated.
new \SearchWP\Integrations\AdvancedCustomFields( $this );
new \SearchWP\Integrations\WooCommerceAdminSearch();
// If this Source is not active we can bail out early.
if ( isset( $params['active'] ) && ! $params['active'] ) {
return;
}
// Prevent invalid IDs from being returned.
if ( ! has_filter( 'searchwp\query', [ $this, 'prevent_invalid_post_ids' ] ) ) {
add_filter( 'searchwp\query', [ $this, 'prevent_invalid_post_ids' ], 10, 2 );
}
// Cycle Posts when they are saved or deleted. This covers:
// - Initial save
// - Edit
// - Delete
// - Status change (e.g. scheduled publishing)
if ( ! has_action( 'save_post', [ $this, 'drop_post' ] ) ) {
add_action( 'save_post', [ $this, 'drop_post' ], 999 );
}
if ( ! has_action( 'delete_post', [ $this, 'drop_post' ] ) ) {
add_action( 'delete_post', [ $this, 'drop_post' ], 999 );
}
if ( ! has_action( 'updated_post_meta', [ $this, 'updated_post_meta' ] ) ) {
add_action( 'updated_post_meta', [ $this, 'updated_post_meta' ], 999, 4 );
}
if ( ! has_action( 'deleted_post_meta', [ $this, 'updated_post_meta' ] ) ) {
add_action( 'deleted_post_meta', [ $this, 'updated_post_meta' ], 999, 4 );
}
if ( ! has_action( 'deleted_term_relationships', [ $this, 'updated_post_term' ] ) ) {
add_action( 'deleted_term_relationships', [ $this, 'updated_post_term' ], 10, 3 );
}
if ( ! has_action( 'added_term_relationship', [ $this, 'updated_post_term' ] ) ) {
add_action( 'added_term_relationship', [ $this, 'updated_post_term' ], 10, 3 );
}
if ( ! has_action( 'edited_term', [ $this, 'updated_taxonomy_term' ] ) ) {
add_action( 'edited_term', [ $this, 'updated_taxonomy_term' ], 10, 3 );
}
}
/**
* Callback to include Taxonomy Names in dropdown by default.
*
* @since 4.1
* @param mixed $keys
* @param mixed $args
* @return mixed|array
*/
public function add_taxonomy_names( $keys, $args ) {
if ( $args['source'] !== $this->name || $args['attribute'] !== 'taxonomy' ) {
return $keys;
}
foreach ( get_object_taxonomies( $this->post_type, 'objects' ) as $taxonomy ) {
$key = $taxonomy->name;
$option = new Option( $taxonomy->name, $taxonomy->label . ' (' . $taxonomy->name . ')' );
// If there's already a match, remove it because we want ours there.
$keys = array_filter( $keys, function( $option ) use ( $key ) {
return $key !== $option->get_value();
});
$keys[] = $option;
}
return $keys;
}
/**
* Callback catch-all to prevent invalid Posts from being returned.
*
* @since 4.0.6
* @param mixed $query The query being executed.
* @param mixed $params Hook parameters.
* @return string[][] The query.
*/
public function prevent_invalid_post_ids( $query, $params ) {
$key = 'searchwp_prevent_invalid_post_ids';
if ( ! array_key_exists( $key, $query['where'] ) ) {
$query['where'][ $key ] = "(SUBSTRING({$params['index_alias']}.source, 1, 5) != 'post"
. SEARCHWP_SEPARATOR . "' OR (SUBSTRING({$params['index_alias']}.source, 1, 5) = 'post"
. SEARCHWP_SEPARATOR . "' AND {$params['index_alias']}.id != '0'))";
}
return $query;
}
/**
* Callback when a taxonomy term is edited.
*
* @since 4.0
* @deprecated 4.2.2 Use updated_post_term()
*
* @param int $object_id Object ID.
* @param array $terms An array of object terms.
* @param array $tt_ids An array of term taxonomy IDs.
* @param string $taxonomy Taxonomy slug.
* @param bool $append Whether to append new terms to the old terms.
* @param array $old_tt_ids Old array of term taxonomy IDs.
*
* @return bool Whether the post was dropped.
*/
public function purge_post_via_term( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ) {
_deprecated_function( __FUNCTION__, '4.2.2', 'updated_post_term()' );
return $this->drop_post( $object_id );
}
/**
* Callback when a taxonomy term is added to or removed from a post.
*
* @since 4.2.2
*
* @param int $object_id Object ID.
* @param array $tt_ids An array of term taxonomy IDs.
* @param string $taxonomy Taxonomy slug.
*
* @return bool Whether the post was dropped.
*/
public function updated_post_term( $object_id, $tt_ids, $taxonomy ) {
$allowed_ajax_requests = (array) apply_filters( 'searchwp\source\post\drop\proper_update_term_request', [ 'delete-tag' ] );
// If doing AJAX check this is a proper request to drop a post.
if (
defined( 'DOING_AJAX' )
&& DOING_AJAX
&& ! (
isset( $_REQUEST['action'] )
&& in_array( $_REQUEST['action'], $allowed_ajax_requests )
)
) {
return false;
}
// If this taxonomy is included in any engine settings drop the post.
if ( Utils::any_engine_has_source_attribute_option( $this->get_attributes()['taxonomy'], $this, $taxonomy ) ) {
do_action( 'searchwp\source\post\drop', [ 'post_id' => $object_id, 'source' => $this ] );
// Drop this post from the index.
\SearchWP::$index->drop( $this, $object_id );
}
}
/**
* Callback when a taxonomy term has been updated.
*
* @since 4.2.3
*
* @param int $term_id Term ID.
* @param int $tt_id Term taxonomy ID.
* @param string $taxonomy Taxonomy slug.
*/
public function updated_taxonomy_term( $term_id, $tt_id, $taxonomy ) {
global $wpdb;
// If this taxonomy is not included in any engine settings bail out.
if ( ! Utils::any_engine_has_source_attribute_option( $this->get_attributes()['taxonomy'], $this, $taxonomy ) ) {
return;
}
$index = \SearchWP::$index;
$tables = $index->get_tables();
$index_table = $tables['index']->table_name;
$status_table = $tables['status']->table_name;
// Fetch all post IDs associated with the taxonomy term.
$term_posts = new \WP_Query(
[
'post_type' => 'any',
'post_status' => 'any',
'fields' => 'ids',
'nopaging' => true,
'tax_query' => [
[
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $term_id,
],
],
]
);
// Split the array of post IDs into batches.
$post_batches = array_chunk( $term_posts->posts, 500 );
// Process each batch separately to prevent database issues.
foreach ( $post_batches as $batch ) {
// Delete the entries in the index and status tables.
$wpdb->query(
$wpdb->prepare( "
DELETE i, s
FROM {$index_table} AS i
LEFT JOIN {$status_table} AS s
ON i.id = s.id
WHERE i.attribute = %s
AND i.id IN (" . implode( ', ', array_fill( 0, count( $batch ), '%s' ) ) . ')',
array_merge( [ 'taxonomy.' . $taxonomy ], $batch )
)
);
}
do_action( 'searchwp\debug\log', "{$taxonomy} id {$term_id} updated dropping posts" );
}
/**
* Returns whether the submitted meta key is used in any Engine.
*
* @param string $meta_key The meta key.
* @param int $object_id The object ID.
* @return bool
*/
public function meta_key_in_use( $meta_key, $object_id = 0 ) {
if ( ! empty( $object_id ) && $this->post_type !== get_post_type( $object_id ) ) {
return false;
}
if ( in_array( $meta_key, Utils::get_ignored_meta_keys( $this->post_type ) ) ) {
return false;
}
return Utils::any_engine_has_source_attribute_option( $this->get_attributes()['meta'], $this, $meta_key );
}
/**
* Callback to drop an entry when a Custom Field is edited.
*
* @param mixed $meta_id ID of metadata entry.
* @param mixed $object_id ID of metadata object.
* @param mixed $meta_key Metadata key
* @param mixed $_meta_value Metadata value.
* @return void
*/
public function updated_post_meta( $meta_id, $object_id, $meta_key, $_meta_value ) {
// Applies only if this meta key applies.
if ( ! $this->meta_key_in_use( $meta_key, $object_id ) ) {
return;
}
// Remove redundant hooks.
remove_action( 'updated_post_meta', [ $this, 'updated_post_meta' ], 999 );
remove_action( 'deleted_post_meta', [ $this, 'updated_post_meta' ], 999 );
remove_action( 'save_post', [ $this, 'drop_post' ], 999 );
remove_action( 'delete_post', [ $this, 'drop_post' ], 999 );
do_action( 'searchwp\source\post\drop', [ 'post_id' => $object_id, 'source' => $this, ] );
// Drop this post from the index.
\SearchWP::$index->drop( $this, $object_id );
}
/**
* Callback from save_post action to drop a post from the index.
*
* @since 4.0
* @param int|string $post_id The post ID to drop.
* @return bool Whether the opration was successful.
*/
public function drop_post( $post_id ) {
if ( ! $this->is_proper_edit_request( $post_id ) ) {
return false;
}
if ( ! $this->is_valid_edit_request( $post_id ) ) {
return false;
}
// Prevent redundant hooks.
remove_action( 'updated_post_meta', [ $this, 'drop_post' ], 999 );
do_action( 'searchwp\source\post\drop', [ 'post_id' => $post_id, 'source' => $this, ] );
// Drop this post from the index.
\SearchWP::$index->drop( $this, $post_id );
}
/**
* Determine whether this request is a valid edit request, meaning the
* post has not already been flagged for editing (to reduce duplicates)
* and the current user has the ability to make this edit.
*
* @since 4.0
* @param int|string $post_id
* @return bool
*/
public function is_valid_edit_request( $post_id ) {
$cache_key = 'searchwp_source_post';
// This action is fired multiple times per request, but we only want to drop a post once.
$cache = (array) wp_cache_get( $cache_key, '' );
if ( in_array( $post_id, $cache, true ) ) {
return false;
}
// This action is fired regardless of post type so we need to check against ours.
if ( $this->post_type !== get_post_type( $post_id ) ) {
return false;
}
// Permissions check.
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return false;
}
// Flag this post as one that has been flagged as handled.
$cache[] = $post_id;
wp_cache_set( $cache_key, $cache, '', 1 );
return true;
}
/**
* Determine whether this request is a proper post edit request as opposed to
* an AJAX call, an autosave, a revision, or Quick Edit.
*
* @since 4.0
* @param int|string $post_id
* @return bool
*/
public function is_proper_edit_request( $post_id ) {
if (
wp_is_post_revision( $post_id )
|| wp_is_post_autosave( $post_id )
|| 'auto-draft' === get_post_status( $post_id )
) {
return false;
}
// Doing AJAX and *not* Quick Editing?
if (
defined( 'DOING_AJAX' )
&& DOING_AJAX
&& ! (
// Quick Edit is still applicable.
isset( $_REQUEST['action'] )
&& 'inline-save' === $_REQUEST['action']
)
) {
return false;
}
if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
return false;
}
return true;
}
/**
* Callback to group meta Attribute Options
*
* @since 4.0
* @param mixed $keys
* @param mixed $args
* @return mixed|array
*/
public function special_meta_keys( $keys, $args ) {
if ( $args['source'] !== $this->name || $args['attribute'] !== 'meta' ) {
return $keys;
}
// If there's a match, remove it.
$keys = array_filter( $keys, function( $option ) {
return '*' !== $option->get_value();
} );
// Add 'Any Meta Key' to the top.
array_unshift( $keys, new Option( '*', __( 'Any Meta Key', 'searchwp' ), 'dashicons dashicons-star-filled' ) );
return $keys;
}
}