@ideasonpurpose/wp-theme-addons 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,527 @@
1
+ <?php
2
+
3
+ /**
4
+ * This file is part of the WordPress Theme Addons.
5
+ * @link https://github.com/ideasonpurpose/wp-theme-addons
6
+ *
7
+ * Formerly https://github.com/ideasonpurpose/wp-related-posts
8
+ */
9
+
10
+ namespace IdeasOnPurpose\WP;
11
+
12
+ /**
13
+ * Rank related content by weighted shared taxonomies, post type, and recency.
14
+ *
15
+ * REST: weights as query args prefixed with weight_ (e.g. weight_topic=5).
16
+ * Aliases: weight_type / weight_post_type → post_type; weight_tag / weight_post_tag → tag.
17
+ *
18
+ * @package IdeasOnPurpose
19
+ */
20
+ class RelatedPosts extends \WP_REST_Controller
21
+ {
22
+ /**
23
+ * Static flag to ensure REST routes are registered only once
24
+ */
25
+ private static $routesRegistered = false;
26
+
27
+ /**
28
+ * Placeholders for mocking
29
+ */
30
+ public $ABSPATH;
31
+ public $WP_DEBUG = false;
32
+
33
+ /**
34
+ * default weights, can be overridden in the constructor
35
+ * Unknown keys default to 1
36
+ */
37
+ public $weights = [
38
+ 'post_tag' => 4,
39
+ 'category' => 3,
40
+ 'post_type' => 2,
41
+ ];
42
+
43
+ /**
44
+ * Default args, these are the minimum required to generate a set of
45
+ * related posts, all arguments will me shallow-merged on top of these.
46
+ * Arrays like weights and post_types will be replaced by merged args.
47
+ */
48
+ public $defaults = [];
49
+
50
+ /**
51
+ * Default number of related posts to return
52
+ */
53
+ public $posts_per_page = 3;
54
+
55
+ /**
56
+ * REST API endpoint components, exposed for testing
57
+ */
58
+ public $rest_base;
59
+ public $rest_base_MINE;
60
+
61
+ /**
62
+ * Used to abstract the global post vs. Posts passed in via $args.
63
+ */
64
+ public $post = null;
65
+
66
+ /**
67
+ * @param array $args Optional defaults override (weights, post, post_types, …)
68
+ */
69
+ public function __construct($args = [])
70
+ {
71
+ $this->ABSPATH = defined('ABSPATH') ? ABSPATH : getcwd();
72
+ $this->WP_DEBUG = defined('WP_DEBUG') && WP_DEBUG;
73
+
74
+ /**
75
+ * Setup the REST route, namespace, route and endpoint base
76
+ * are defined in the constructor so they can be mocked.
77
+ */
78
+ $this->namespace = 'ideasonpurpose/v1';
79
+ $this->rest_base = 'related_posts';
80
+ $this->rest_base_MINE = "{$this->namespace}/{$this->rest_base}";
81
+ add_action('rest_api_init', [$this, 'registerRestRoutes']);
82
+
83
+ $this->setDefaults();
84
+ $cleanArgs = $this->normalizeArgs($args);
85
+ if ($cleanArgs && isset($cleanArgs['weights'])) {
86
+ $this->weights = $cleanArgs['weights'];
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Set default args. These are the minimum required to query for related posts
92
+ * and all user input args will be merged on top of the baseline in $this->defaults
93
+ * @return void
94
+ */
95
+ public function setDefaults()
96
+ {
97
+ global $post;
98
+ $post_types = get_post_type() ? [get_post_type()] : [];
99
+ $this->defaults = [
100
+ 'post' => $post,
101
+ 'post_types' => $post_types,
102
+ 'weights' => [
103
+ 'post_tag' => 4,
104
+ 'category' => 3,
105
+ 'post_type' => 2,
106
+ ],
107
+ 'posts_per_page' => 3,
108
+ 'offset' => 0,
109
+ 'has_post_thumbnail' => false,
110
+ ];
111
+ }
112
+
113
+ /**
114
+ * Register REST routes to return Related Posts
115
+ */
116
+ public function registerRestRoutes()
117
+ {
118
+ if (!self::$routesRegistered) {
119
+ register_rest_route($this->namespace, "/{$this->rest_base}/(?P<id>[0-9]+)", [
120
+ 'methods' => \WP_REST_Server::READABLE,
121
+ 'callback' => [$this, 'restResponse'],
122
+ 'permission_callback' => '__return_true',
123
+ ]);
124
+ self::$routesRegistered = true;
125
+ }
126
+ }
127
+
128
+ public function restResponse(\WP_REST_Request $req)
129
+ {
130
+ $id = $req->get_param('id');
131
+ $count = $req->get_param('count') ?? $this->posts_per_page;
132
+
133
+ $weights = [];
134
+ foreach ($req->get_params() as $param => $val) {
135
+ $parts = preg_split('/_/', strtolower($param), 2, PREG_SPLIT_NO_EMPTY);
136
+
137
+ if (($parts[0] ?? null) === 'weight' && isset($parts[1]) && is_numeric($val)) {
138
+ $key = preg_replace('/^post_/', '', $parts[1]);
139
+ $weights[$key] = max(0, min(7, (int) $val));
140
+ }
141
+ }
142
+
143
+ $posts = $this->get([
144
+ 'post' => $id,
145
+ 'posts_per_page' => $count,
146
+ 'weights' => array_merge($this->weights, $weights),
147
+ ]);
148
+
149
+ /**
150
+ * Generate a set of post_type-specific controllers. Doing this in
151
+ * the following post loop would recreate the multiple controllers
152
+ * for the same post_type.
153
+ */
154
+ $post_types = array_unique(wp_list_pluck($posts, 'post_type'));
155
+ $controllers = [];
156
+ foreach ($post_types as $post_type) {
157
+ $controllers[$post_type] = new \WP_REST_Posts_Controller($post_type);
158
+ }
159
+
160
+ /**
161
+ * Convert WP_Post objects to REST collection items
162
+ */
163
+ $data = [];
164
+ foreach ($posts as $post) {
165
+ $response = $controllers[$post->post_type]->prepare_item_for_response(
166
+ $post,
167
+ new \WP_REST_Request(),
168
+ );
169
+
170
+ $data[] = $this->prepare_response_for_collection($response);
171
+ }
172
+
173
+ return rest_ensure_response($data);
174
+ }
175
+
176
+ /**
177
+ * Transforms an $args array to ensure valid properties.
178
+ * @return array
179
+ */
180
+ public function normalizeArgs($rawArgs)
181
+ {
182
+ global $post;
183
+
184
+ $args = is_array($rawArgs) ? $rawArgs : $this->defaults;
185
+ $cleanArgs = [];
186
+ /**
187
+ * Ensure a $post is set and is a valid WP_POST object
188
+ */
189
+ $cleanArgs['post'] = array_key_exists('post', $args) ? $args['post'] : $post;
190
+ $cleanArgs['post'] = get_post($cleanArgs['post']); // returns a WP_Post or null
191
+
192
+ if (!$cleanArgs['post']) {
193
+ $latest_post = get_posts(['post_type' => 'any', 'posts_per_page' => 1]);
194
+ $cleanArgs['post'] = array_pop($latest_post);
195
+ }
196
+
197
+ if (
198
+ get_post_type($cleanArgs['post']) === 'revision' &&
199
+ $cleanArgs['post']->post_parent !== 0
200
+ ) {
201
+ $cleanArgs['post'] = get_post($cleanArgs['post']->post_parent);
202
+ }
203
+
204
+ if (!$cleanArgs['post']) {
205
+ return false;
206
+ }
207
+
208
+ /**
209
+ * Ensure weights is an array of integers
210
+ */
211
+ if (array_key_exists('weights', $args) && is_array($args['weights'])) {
212
+ foreach ($args['weights'] as $slug => $val) {
213
+ if (is_numeric($val)) {
214
+ $cleanArgs['weights'][$slug] = (int) $val;
215
+ }
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Ensure post_types is a unique array of strings
221
+ *
222
+ * TODO: This can not be empty, should not include 'attachment'
223
+ */
224
+ if (array_key_exists('post_types', $args) && is_array($args['post_types'])) {
225
+ $cleanArgs['post_types'] = [];
226
+ foreach ($args['post_types'] as $post_type) {
227
+ if (is_string($post_type) && $post_type !== 'attachment') {
228
+ $cleanArgs['post_types'][] = $post_type;
229
+ }
230
+ }
231
+ $cleanArgs['post_types'] = array_unique($cleanArgs['post_types']);
232
+ if (empty($cleanArgs['post_types'])) {
233
+ $cleanArgs['post_types'] = [get_post_type($post)];
234
+ }
235
+ }
236
+
237
+ if (array_key_exists('has_post_thumbnail', $args)) {
238
+ $cleanArgs['has_post_thumbnail'] = filter_var(
239
+ $args['has_post_thumbnail'],
240
+ FILTER_VALIDATE_BOOLEAN,
241
+ );
242
+ }
243
+
244
+ if (array_key_exists('offset', $args)) {
245
+ if (is_numeric($args['offset'])) {
246
+ $cleanArgs['offset'] = (int) $args['offset'];
247
+ }
248
+ }
249
+
250
+ if (array_key_exists('posts_per_page', $args)) {
251
+ if (is_numeric($args['posts_per_page'])) {
252
+ $min = 1;
253
+ $max = 20;
254
+ $val = (int) $args['posts_per_page'];
255
+ $cleanArgs['posts_per_page'] = max($min, min($val, $max));
256
+ }
257
+ }
258
+
259
+ $cleanArgs = array_merge($this->defaults, $cleanArgs);
260
+ return $cleanArgs;
261
+ }
262
+
263
+ /**
264
+ * Returns a copy of the input $weights array with all values clamped between $min and $max
265
+ * @param array $weights
266
+ * @param int $min
267
+ * @param int $max
268
+ * @return array
269
+ */
270
+ public function clampWeights($weights, $min = 0, $max = 7)
271
+ {
272
+ $clamped = [];
273
+ foreach ($weights as $key => $value) {
274
+ $clamped[$key] = max($min, min((int) $value, $max));
275
+ }
276
+ return $clamped;
277
+ }
278
+
279
+ public function getTransientName($cleanArgs)
280
+ {
281
+ $basis = [
282
+ 'id' => $cleanArgs['post']->ID,
283
+ 'weights' => $cleanArgs['weights'],
284
+ 'post_types' => $cleanArgs['post_types'],
285
+ ];
286
+
287
+ return 'related_posts_' . md5(json_encode($basis));
288
+ }
289
+
290
+ /**
291
+ * Gather and rank related posts for a given WP_POST based on the post
292
+ * used to initialize RelatedPosts
293
+ *
294
+ * Store the result in a transient derived from the Post ID and weightings
295
+ * @return array Array of related WP_Post objects
296
+ */
297
+ public function fetchPosts($cleanArgs): array
298
+ {
299
+ /*
300
+ * store posts in an 8-hour transient to conserve queries and to prevent
301
+ * spiders from thinking the page is changing too often.
302
+ */
303
+ $transientName = $this->getTransientName($cleanArgs);
304
+ $posts = $this->WP_DEBUG ? false : get_transient($transientName);
305
+ if ($posts === false) {
306
+ $posts = $this->collectPosts($cleanArgs);
307
+ // TODO: Make transient duration configurable?
308
+ set_transient($transientName, $posts, 8 * HOUR_IN_SECONDS);
309
+ }
310
+ return $posts;
311
+ }
312
+
313
+ /**
314
+ * Run a bunch of queries to collect related posts, then rank posts by frequency
315
+ *
316
+ * Queries:
317
+ * Same type
318
+ * matching tags
319
+ * last 12 of same type
320
+ * last 12 of all types
321
+ *
322
+ * TODO: Make that '12' number configurable
323
+ *
324
+ * @param array $args options container, may include a post (WP_POST) and weights
325
+ */
326
+ public function collectPosts(array $cleanArgs): array
327
+ {
328
+ /**
329
+ * This will hold an array of post IDs which will be added multiple times
330
+ * after being merged in with arrayMergeWeighted().
331
+ */
332
+ $postBucket = [];
333
+
334
+ $post = $cleanArgs['post'];
335
+ $post_types = $cleanArgs['post_types'];
336
+
337
+ $taxonomies = get_object_taxonomies($post->post_type, 'objects');
338
+
339
+ $thumb_query = ['key' => '_thumbnail_id', 'compare' => 'EXISTS'];
340
+ $meta_query = $cleanArgs['has_post_thumbnail'] ? [$thumb_query] : [];
341
+
342
+ /**
343
+ * Collect posts with the same terms across all of this object's taxonomies
344
+ * TODO: Filter taxonomies that are not weighted?
345
+ */
346
+ foreach ($taxonomies as $slug => $tax) {
347
+ $terms = get_the_terms($post->ID, $slug);
348
+ if ($terms) {
349
+ foreach ($terms as $term) {
350
+ $posts = get_posts([
351
+ 'post__not_in' => [$post->ID],
352
+ 'posts_per_page' => 12,
353
+ 'orderby' => ['date' => 'DESC'],
354
+ 'post_status' => 'publish',
355
+ 'post_type' => $post_types,
356
+ 'tax_query' => [
357
+ [
358
+ 'taxonomy' => $slug,
359
+ 'field' => 'slug',
360
+ 'terms' => [$term->slug],
361
+ ],
362
+ ],
363
+ 'meta_query' => $meta_query,
364
+ ]);
365
+ $ids = wp_list_pluck($posts, 'ID');
366
+ $postBucket = $this->arrayMergeWeighted($postBucket, $ids, $slug);
367
+ }
368
+ }
369
+ }
370
+
371
+ /**
372
+ * If the posts's post_type is included in post_types, collect the most recent posts of the same post_type
373
+ */
374
+ if (in_array($post->post_type, $post_types)) {
375
+ $posts = get_posts([
376
+ 'post_type' => $post->post_type,
377
+ 'post__not_in' => [$post->ID],
378
+ 'posts_per_page' => 12,
379
+ 'orderby' => ['date' => 'DESC'],
380
+ 'meta_query' => $meta_query,
381
+ ]);
382
+ $ids = wp_list_pluck($posts, 'ID');
383
+ $postBucket = $this->arrayMergeWeighted($postBucket, $ids, 'post_type');
384
+ }
385
+
386
+ /**
387
+ * Get 12 most recent posts in $post_types
388
+ *
389
+ * TODO: Should this happen for each post_type?
390
+ */
391
+ $posts = get_posts([
392
+ 'post_type' => $post_types,
393
+ 'post__not_in' => [$post->ID],
394
+ 'posts_per_page' => 12,
395
+ 'post_status' => 'publish',
396
+ 'orderby' => ['date' => 'DESC'],
397
+ 'meta_query' => $meta_query,
398
+ ]);
399
+ $ids = wp_list_pluck($posts, 'ID');
400
+ $postBucket = $this->arrayMergeWeighted($postBucket, $ids, 'date');
401
+
402
+ /**
403
+ * Create a lookup table array with IDs and occurrence counts.
404
+ */
405
+ $counts = array_count_values($postBucket);
406
+
407
+ if ($this->WP_DEBUG) {
408
+ $bucketCount = count($postBucket);
409
+ $countsCount = count($counts);
410
+ error_log(
411
+ "RelatedPosts collected {$bucketCount} occurrences of {$countsCount} posts.",
412
+ );
413
+ }
414
+
415
+ // TODO: Extract total number of unique collected IDs here for debugging
416
+
417
+ $rankedPosts = [];
418
+ foreach ($counts as $key => $count) {
419
+ $thePost = get_post($key);
420
+ $rankedPosts[$key] = [
421
+ 'count' => $count,
422
+ 'post_date' => $thePost->post_date,
423
+ 'post' => $thePost,
424
+ ];
425
+ }
426
+
427
+ /**
428
+ * Sort rankedPosts by count DESC, then date DESC
429
+ */
430
+ uasort($rankedPosts, function ($a, $b) {
431
+ $cmp = $b['count'] - $a['count'];
432
+ if ($cmp === 0) {
433
+ $cmp = strcmp($b['post_date'], $a['post_date']);
434
+ }
435
+ return $cmp;
436
+ });
437
+
438
+ return array_map(function ($n) {
439
+ return $n['post'];
440
+ }, $rankedPosts);
441
+ }
442
+
443
+ /**
444
+ * fetches a weight integer from $this->weights
445
+ * unknown keys default to 1
446
+ * tags is translated to post_tag
447
+ * @param string $slug the taxonomy or type of query to weight
448
+ * @return integer an integer weight
449
+ */
450
+ public function getWeight($slug)
451
+ {
452
+ // remap 'post_tag' to 'tag'
453
+ // if ($slug === 'post_tag') {
454
+ // $slug = 'tag';
455
+ // }
456
+ // remap 'tag' to 'post_tag'
457
+ if ($slug === 'tag') {
458
+ $slug = 'post_tag';
459
+ }
460
+
461
+ return $this->weights[$slug] ?? 1;
462
+
463
+ // $weight = 1;
464
+ // if (array_key_exists($slug, $this->weights)) {
465
+ // $weight = $this->weights[$slug];
466
+ // }
467
+ // return $weight;
468
+ }
469
+
470
+ /**
471
+ * wrapper for array_merge which uses weights from $this->getWeight
472
+ * @param array $base array to merge into
473
+ * @param array $merge array to merge
474
+ * @param string $slug taxonomy or type of query to weight
475
+ * @return array the merged array
476
+ */
477
+ public function arrayMergeWeighted($base, $merge, $slug)
478
+ {
479
+ $output = $base;
480
+ $weight = $this->getWeight($slug);
481
+ for ($i = 0; $i < $weight; $i++) {
482
+ $output = array_merge($output, $merge);
483
+ }
484
+ return $output;
485
+ }
486
+
487
+ /**
488
+ * Get related posts
489
+ * @param array|int $args Options array, or legacy posts_per_page integer
490
+ * @return array Returns an array of posts, or an empty array
491
+ */
492
+ public function get($args = [])
493
+ {
494
+ $cleanArgs = $this->normalizeArgs($args);
495
+
496
+ if (!$cleanArgs) {
497
+ /**
498
+ * If args can't be parsed, normalizeArgs will return false
499
+ */
500
+ return [];
501
+ }
502
+ /**
503
+ * Handle legacy first-arg is a number, apply back to default $cleanArgs
504
+ */
505
+ if (is_numeric($args)) {
506
+ $cleanArgs['posts_per_page'] = $args;
507
+ }
508
+
509
+ /**
510
+ * Ranking reads $this->weights via getWeight(); sync from this call's args
511
+ */
512
+ if (isset($cleanArgs['weights']) && is_array($cleanArgs['weights'])) {
513
+ $this->weights = $cleanArgs['weights'];
514
+ }
515
+
516
+ $offset = $cleanArgs['offset'] ?? 0;
517
+ $per_page = $cleanArgs['posts_per_page'] ?? $this->posts_per_page;
518
+ $posts = array_slice($this->fetchPosts($cleanArgs), $offset, $per_page);
519
+
520
+ return $posts;
521
+ }
522
+ }
523
+
524
+ /**
525
+ * Reference links
526
+ * @link https://developer.wordpress.org/rest-api/extending-the-rest-api/controller-classes/
527
+ */
@@ -0,0 +1,36 @@
1
+ import { store as coreStore } from "@wordpress/core-data";
2
+ import { useMemo } from "@wordpress/element";
3
+ import { useSelect } from "@wordpress/data";
4
+
5
+ /**
6
+ * Call this to initialize the data-store so a plain select('core').getPostType has data to pull from
7
+ *
8
+ * Lifted directly from the undocumented and not exported usePublicPostTypes() here:
9
+ * @link https://github.com/WordPress/gutenberg/blob/d913ca150ba2c616e16134447d6e61e7704a7962/packages/edit-site/src/components/add-new-template/utils.js#L91-L113
10
+ *
11
+ * NOTE: Importing usePostTypes from @wordpress/block-library/src/query/utils silently broke the whole block variation.
12
+ * Don't use this:
13
+ * @link https://github.com/WordPress/gutenberg/blob/28847b04ce121fd333ee364a6525d2ca7f969e10/packages/block-library/src/query/utils.js#L93-L128
14
+ */
15
+ export function usePublicPostTypes() {
16
+ const postTypes = useSelect(
17
+ (select) => select(coreStore).getPostTypes({ per_page: -1 }),
18
+ [],
19
+ );
20
+ return useMemo(() => {
21
+ const excludedPostTypes = ["attachment"];
22
+ return postTypes
23
+ ?.filter(
24
+ ({ viewable, slug }) => viewable && !excludedPostTypes.includes(slug),
25
+ )
26
+ .sort((a, b) => {
27
+ // Sort post types alphabetically by name,
28
+ // but exclude the built-in 'post' type from sorting.
29
+ if (a.slug === "post" || b.slug === "post") {
30
+ return 0;
31
+ }
32
+
33
+ return a.name.localeCompare(b.name);
34
+ });
35
+ }, [postTypes]);
36
+ }
@@ -0,0 +1,21 @@
1
+ import { store as coreStore } from "@wordpress/core-data";
2
+ import { useMemo } from "@wordpress/element";
3
+ import { useSelect } from "@wordpress/data";
4
+
5
+ /**
6
+ * Call this to initialize the data-store so a plain select('core').getTaxonomy has data to pull from
7
+ *
8
+ * Lifted directly from the undocumented and not exported usePublicTaxonomies here:
9
+ * @link https://github.com/WordPress/gutenberg/blob/d913ca150ba2c616e16134447d6e61e7704a7962/packages/edit-site/src/components/add-new-template/utils.js#L115-L125
10
+ */
11
+ export function usePublicTaxonomies() {
12
+ const taxonomies = useSelect(
13
+ (select) => select(coreStore).getTaxonomies({ per_page: -1 }),
14
+ [],
15
+ );
16
+ return useMemo(() => {
17
+ return taxonomies?.filter(
18
+ ({ visibility }) => visibility?.publicly_queryable,
19
+ );
20
+ }, [taxonomies]);
21
+ }
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@ideasonpurpose/wp-theme-addons",
3
+ "version": "0.2.2",
4
+ "description": "WordPress Block Editor add-ons — JavaScript blocks, utilities, and PHP components",
5
+ "keywords": [
6
+ "wordpress",
7
+ "gutenberg",
8
+ "block-editor",
9
+ "block-variation",
10
+ "themes"
11
+ ],
12
+ "homepage": "https://github.com/ideasonpurpose/wp-theme-addons",
13
+ "bugs": {
14
+ "url": "https://github.com/ideasonpurpose/wp-theme-addons/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/ideasonpurpose/wp-theme-addons.git"
19
+ },
20
+ "license": "MIT",
21
+ "author": "Ideas On Purpose (https://www.ideasonpurpose.com/)",
22
+ "contributors": [
23
+ {
24
+ "name": "Joe Maller",
25
+ "email": "joe@ideasonpurpose.com"
26
+ }
27
+ ],
28
+ "type": "module",
29
+ "exports": "./index.js",
30
+ "main": "index.js",
31
+ "directories": {
32
+ "lib": "lib"
33
+ },
34
+ "files": [
35
+ "index.js",
36
+ "lib",
37
+ "editor",
38
+ "CssLocalProps",
39
+ "README.md"
40
+ ],
41
+ "scripts": {
42
+ "version": "version-everything && git add -u"
43
+ },
44
+ "devDependencies": {
45
+ "@ideasonpurpose/prettier-config": "^1.1.1",
46
+ "@ideasonpurpose/stylelint-config": "^1.1.6",
47
+ "@prettier/plugin-php": "^0.25.0",
48
+ "@types/wordpress__block-editor": "^15.0.6",
49
+ "@wordpress/compose": "^8.3.0",
50
+ "@wordpress/hooks": "^4.50.0",
51
+ "prettier": "^3.9.4",
52
+ "version-everything": "^0.12.2"
53
+ },
54
+ "prettier": "@ideasonpurpose/prettier-config",
55
+ "stylelint": {
56
+ "extends": "@ideasonpurpose/stylelint-config"
57
+ },
58
+ "version-everything": {
59
+ "files": [
60
+ "README.md"
61
+ ]
62
+ }
63
+ }