PluginProbe ʕ •ᴥ•ʔ
Search Regex / trunk
Search Regex vtrunk
trunk 1.4.12 1.4.13 1.4.14 1.4.15 1.4.16 2.0 2.0.1 2.1 2.2 2.2.1 2.3 2.3.1 2.3.2 2.3.3 2.4 2.4.1 3.0.0 3.0.1 3.0.2 3.0.3 3.0.4 3.0.5 3.0.6 3.0.7 3.0.8 3.1 3.1.1 3.1.2 3.2 3.3 3.3.0 3.3.1 3.4 3.4.1 3.4.2
search-regex / includes / source / class-has-terms.php
search-regex / includes / source Last commit date
core 4 months ago class-autocomplete.php 6 months ago class-convert-values.php 5 months ago class-has-meta.php 5 months ago class-has-terms.php 5 months ago class-manager.php 5 months ago class-source.php 5 months ago
class-has-terms.php
103 lines
1 <?php
2
3 namespace SearchRegex\Source;
4
5 use SearchRegex\Context\Type;
6 use SearchRegex\Plugin;
7 use WP_Term;
8
9 /**
10 * Trait to add term support to a source
11 *
12 * @phpstan-type TermItem array{value: string, label: string}
13 * @phpstan-type TermColumn array{column: string, items: list<TermItem>}
14 */
15 trait Has_Terms {
16 /**
17 * Look for term changes and process them
18 *
19 * @param int $row_id Row ID.
20 * @param string $type Type.
21 * @param array<string, mixed> $updates Array of updates.
22 * @return void
23 */
24 protected function process_terms( $row_id, $type, array $updates ) {
25 foreach ( $updates as $column => $update ) {
26 if ( $column === 'category' || $column === 'post_tag' ) {
27 $this->set_terms( $row_id, $column, $update );
28 }
29 }
30 }
31
32 /**
33 * Get the terms as an array of value/label
34 *
35 * @param array<WP_Term> $terms Terms.
36 * @return TermColumn[]
37 */
38 private function get_terms( array $terms ) {
39 $cats = [];
40 $tags = [];
41 $extra = [];
42
43 foreach ( $terms as $term ) {
44 if ( $term->taxonomy === 'category' ) {
45 $cats[] = [
46 'value' => $term->slug,
47 'label' => $term->name,
48 ];
49 } else {
50 $tags[] = [
51 'value' => $term->slug,
52 'label' => $term->name,
53 ];
54 }
55 }
56
57 if ( count( $tags ) > 0 ) {
58 $extra[] = [
59 'column' => 'post_tag',
60 'items' => $tags,
61 ];
62 }
63
64 if ( count( $cats ) > 0 ) {
65 $extra[] = [
66 'column' => 'category',
67 'items' => $cats,
68 ];
69 }
70
71 return $extra;
72 }
73
74 /**
75 * Perform term changes on an object
76 *
77 * @param int $row_id Row ID.
78 * @param string $column Column to change.
79 * @param array<string, mixed> $update Changes.
80 * @return void
81 */
82 private function set_terms( $row_id, $column, array $update ) {
83 // Get all term IDs that haven't changed
84 $term_ids = array_map(
85 fn( $item ) => intval( $item->get_value(), 10 ),
86 $update['same']
87 );
88
89 // Get all term IDs that have changed
90 foreach ( $update['change'] as $change ) {
91 if ( $change->get_type() === Type\Add::TYPE_ADD ) {
92 $term_ids[] = intval( $change->get_value(), 10 );
93 }
94 }
95
96 $this->log_save( 'term ' . $column, $term_ids );
97
98 if ( Plugin\Settings::init()->can_save() ) {
99 wp_set_object_terms( $row_id, $term_ids, $column, false );
100 }
101 }
102 }
103