@wp-operations/wp-ops 0.2.0 → 0.3.1

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.
Files changed (122) hide show
  1. package/README.md +30 -27
  2. package/bin/wp-app.js +2 -0
  3. package/bin/wp-code.js +2 -0
  4. package/bin/wp-ide.js +2 -0
  5. package/package.json +12 -3
  6. package/src/commands/platform.js +16 -2
  7. package/src/commands/sandbox.js +3 -3
  8. package/src/main.js +10 -4
  9. package/wp-operations/CHANGELOG.md +14 -0
  10. package/wp-operations/README.md +39 -0
  11. package/wp-operations/agents/builder/AGENT.md +15 -0
  12. package/wp-operations/assets/admin.css +631 -0
  13. package/wp-operations/assets/admin.js +614 -0
  14. package/wp-operations/assets/app/app.css +1 -0
  15. package/wp-operations/assets/app/app.js +70 -0
  16. package/wp-operations/assets/app/fonts/inter-medium.woff +0 -0
  17. package/wp-operations/assets/app/fonts/inter-regular.woff +0 -0
  18. package/wp-operations/assets/app/fonts/inter-semibold.woff +0 -0
  19. package/wp-operations/assets/app/login.css +42 -0
  20. package/wp-operations/assets/brand/icon.svg +20 -0
  21. package/wp-operations/assets/brand/mark.svg +19 -0
  22. package/wp-operations/assets/editors/audiobook.css +311 -0
  23. package/wp-operations/assets/editors/audiofile.css +286 -0
  24. package/wp-operations/assets/editors/course.css +701 -0
  25. package/wp-operations/assets/editors/course.js +698 -0
  26. package/wp-operations/assets/editors/faq.css +258 -0
  27. package/wp-operations/assets/editors/faq.js +196 -0
  28. package/wp-operations/assets/editors/interactive.css +220 -0
  29. package/wp-operations/assets/editors/interactive.js +378 -0
  30. package/wp-operations/assets/editors/media-sources.css +3 -0
  31. package/wp-operations/assets/editors/media-sources.js +40 -0
  32. package/wp-operations/assets/editors/open-media.css +114 -0
  33. package/wp-operations/assets/editors/open-media.js +182 -0
  34. package/wp-operations/assets/editors/thumbnails.css +335 -0
  35. package/wp-operations/assets/editors/thumbnails.js +447 -0
  36. package/wp-operations/assets/editors/translator.css +818 -0
  37. package/wp-operations/functions.php +24 -0
  38. package/wp-operations/index.php +14 -0
  39. package/wp-operations/platform.json +1836 -0
  40. package/wp-operations/skills/ai-development-guardrails/SKILL.md +49 -0
  41. package/wp-operations/skills/gutenberg-reference/SKILL.md +45 -0
  42. package/wp-operations/skills/js-tooling-for-themes/SKILL.md +51 -0
  43. package/wp-operations/skills/tailwind-for-wp/SKILL.md +62 -0
  44. package/wp-operations/skills/wp-clean-classic-themes/SKILL.md +112 -0
  45. package/wp-operations/skills/wp-psr4-plugins/SKILL.md +2043 -0
  46. package/wp-operations/skills/wp-security/SKILL.md +90 -0
  47. package/wp-operations/src/Admin.php +78 -0
  48. package/wp-operations/src/App/Access.php +57 -0
  49. package/wp-operations/src/App/Admin.php +442 -0
  50. package/wp-operations/src/App/App.php +157 -0
  51. package/wp-operations/src/App/Apps.php +379 -0
  52. package/wp-operations/src/App/Bundle.php +111 -0
  53. package/wp-operations/src/App/Contents.php +676 -0
  54. package/wp-operations/src/App/Engine.php +554 -0
  55. package/wp-operations/src/App/Github.php +308 -0
  56. package/wp-operations/src/App/Module.php +23 -0
  57. package/wp-operations/src/App/Ops.php +470 -0
  58. package/wp-operations/src/App/Packages.php +289 -0
  59. package/wp-operations/src/App/Rest.php +539 -0
  60. package/wp-operations/src/App/Sandboxes.php +206 -0
  61. package/wp-operations/src/App/Store.php +104 -0
  62. package/wp-operations/src/App/Usage.php +268 -0
  63. package/wp-operations/src/Config.php +249 -0
  64. package/wp-operations/src/Content/Editor.php +223 -0
  65. package/wp-operations/src/Content/Fields.php +681 -0
  66. package/wp-operations/src/Content/Scoring.php +253 -0
  67. package/wp-operations/src/Content/Structure.php +293 -0
  68. package/wp-operations/src/Content/Types.php +150 -0
  69. package/wp-operations/src/Content/Uploads.php +50 -0
  70. package/wp-operations/src/Editors/AudiobookAuthor.php +61 -0
  71. package/wp-operations/src/Editors/AudiobookChapters.php +632 -0
  72. package/wp-operations/src/Editors/AudiobookCover.php +235 -0
  73. package/wp-operations/src/Editors/Audiofile.php +462 -0
  74. package/wp-operations/src/Editors/Course.php +784 -0
  75. package/wp-operations/src/Editors/Ebook.php +242 -0
  76. package/wp-operations/src/Editors/Editors.php +44 -0
  77. package/wp-operations/src/Editors/Faq.php +237 -0
  78. package/wp-operations/src/Editors/Files.php +139 -0
  79. package/wp-operations/src/Editors/Interactive/Builder.php +103 -0
  80. package/wp-operations/src/Editors/Interactive/Card.php +76 -0
  81. package/wp-operations/src/Editors/Interactive/Editor.php +42 -0
  82. package/wp-operations/src/Editors/Interactive/Field.php +272 -0
  83. package/wp-operations/src/Editors/Interactive/Map.php +84 -0
  84. package/wp-operations/src/Editors/Interactive/Models.php +227 -0
  85. package/wp-operations/src/Editors/Interactive/Report.php +59 -0
  86. package/wp-operations/src/Editors/Interactive/Save.php +323 -0
  87. package/wp-operations/src/Editors/Interactive/Scoring.php +244 -0
  88. package/wp-operations/src/Editors/Interactive/Structure.php +195 -0
  89. package/wp-operations/src/Editors/Legal.php +235 -0
  90. package/wp-operations/src/Editors/OpenMedia.php +140 -0
  91. package/wp-operations/src/Editors/OriginalTitle.php +112 -0
  92. package/wp-operations/src/Editors/Sources.php +28 -0
  93. package/wp-operations/src/Editors/Thumbnails/Admin.php +306 -0
  94. package/wp-operations/src/Editors/Thumbnails/Ajax.php +163 -0
  95. package/wp-operations/src/Editors/Thumbnails/Box.php +188 -0
  96. package/wp-operations/src/Editors/Thumbnails/Storage.php +228 -0
  97. package/wp-operations/src/Editors/Translator/Admin.php +913 -0
  98. package/wp-operations/src/Editors/Translator/Api.php +63 -0
  99. package/wp-operations/src/Editors/Translator/Bar.php +83 -0
  100. package/wp-operations/src/Editors/Translator/Fields.php +273 -0
  101. package/wp-operations/src/Editors/Translator/Storage.php +131 -0
  102. package/wp-operations/src/Editors/Translator/Thumbnail.php +215 -0
  103. package/wp-operations/src/Identity.php +104 -0
  104. package/wp-operations/src/Languages.php +45 -0
  105. package/wp-operations/src/Lockdown.php +85 -0
  106. package/wp-operations/src/Modules/Apps/Admin.php +472 -0
  107. package/wp-operations/src/Modules/Apps/Api.php +193 -0
  108. package/wp-operations/src/Modules/Apps/Apps.php +279 -0
  109. package/wp-operations/src/Modules/Apps/Formatters.php +478 -0
  110. package/wp-operations/src/Modules/Apps/Schemes.php +248 -0
  111. package/wp-operations/src/Modules/Apps/Table.php +101 -0
  112. package/wp-operations/src/Modules/Thumbnails.php +68 -0
  113. package/wp-operations/src/Modules/Translations.php +133 -0
  114. package/wp-operations/src/Platform.php +59 -0
  115. package/wp-operations/src/Setup.php +273 -0
  116. package/wp-operations/src/Status.php +99 -0
  117. package/wp-operations/src/Storage/Client.php +168 -0
  118. package/wp-operations/src/Storage/Offload.php +120 -0
  119. package/wp-operations/src/Storage/Settings.php +166 -0
  120. package/wp-operations/src/Storage/Storage.php +35 -0
  121. package/wp-operations/src/Updates.php +151 -0
  122. package/wp-operations/style.css +11 -0
@@ -0,0 +1,2043 @@
1
+ ---
2
+ name: wp-psr4-plugins
3
+ description: >
4
+ Ultimate handbook for strict PSR-4 WordPress plugin development.
5
+ Pure PSR-4 autoload — no files autoload, no bootstrap.php.
6
+ Covers composer.json standard, hook engine, naming, strict typing, security,
7
+ posts, meta, taxonomies, users, options, custom DB, REST API, remote HTTP,
8
+ AJAX, cron, and inter-package extension. Max strict — designed for modern
9
+ PHP compilers and translators.
10
+ references:
11
+ - https://packagist.org/about
12
+ - https://getcomposer.org/doc/04-schema.md
13
+ - https://developer.wordpress.org/plugins/hooks/
14
+ - https://developer.wordpress.org/plugins/hooks/actions/
15
+ - https://developer.wordpress.org/plugins/hooks/filters/
16
+ - https://developer.wordpress.org/plugins/hooks/custom-hooks/
17
+ - https://developer.wordpress.org/apis/security/
18
+ - https://developer.wordpress.org/apis/security/nonces/
19
+ - https://developer.wordpress.org/plugins/wordpress-org/common-issues/
20
+ - https://learn.wordpress.org/lesson/developing-with-hooks/
21
+ ---
22
+
23
+ ## 0. Philosophy
24
+
25
+ WordPress is an **event-driven engine**. Everything is a hook. You never call another
26
+ package's class method directly — you fire an action or apply a filter, and listeners
27
+ respond. PSR-4 autoloading handles class resolution. Hooks handle execution wiring.
28
+ These two systems together eliminate manual `require`, sprawling bootstrap logic, and
29
+ cross-package direct calls.
30
+
31
+ Code in this skill is serverside WordPress engine code — custom post types, importers,
32
+ AJAX handlers, REST endpoints, admin pages. Not theme templates, not block editor,
33
+ not frontend JS frameworks.
34
+
35
+ ---
36
+
37
+ ## 0.1 WordPress & ClassicPress
38
+
39
+ **WordPress** is the world's leading open-source CMS, currently at 6.x, actively
40
+ developed with a large ecosystem.
41
+
42
+ **ClassicPress** is a community-led fork of WordPress — version 2.x tracks WordPress
43
+ 6.x compatibility while permanently removing Gutenberg and Full Site Editing.
44
+ Latest stable: 2.7.0.
45
+
46
+ This skill targets **WordPress backend development**: hooks, CPTs, meta, taxonomies,
47
+ REST, AJAX, cron, options, and custom DB. It is fully compatible with both WordPress
48
+ and ClassicPress 2.x.
49
+
50
+ **Gutenberg, the Block Editor, and Full Site Editing are out of scope** — not covered,
51
+ not used, not assumed. ClassicPress does not include them. This skill does not need them.
52
+
53
+ ---
54
+
55
+ ## 1. Composer Package Standard
56
+
57
+ ### `composer.json`
58
+
59
+ ```json
60
+ {
61
+ "name": "vendor/package-name",
62
+ "type": "library",
63
+ "description": "One line description.",
64
+ "require": {
65
+ "php": ">=8.0"
66
+ },
67
+ "autoload": {
68
+ "psr-4": {
69
+ "Vendor\\Package\\": "src/"
70
+ }
71
+ }
72
+ }
73
+ ```
74
+
75
+ **Rules:**
76
+ - `name` is `vendor/package`. Lowercase letters, numbers, `.`, `-`, `_` only.
77
+ - **Never** include `"version"`. Versions come from VCS tags (`1.0.0`, `v1.0.0`).
78
+ - `"type": "library"` always.
79
+ - `src/` is the PSR-4 root. Never `lib/`, `includes/`, `classes/`.
80
+ - `require` lists only real runtime dependencies. Dev tools go in `require-dev`.
81
+ - **No `files` autoload.** No `bootstrap.php`. No `require_once` hacks. Pure PSR-4.
82
+ - Omit empty or unknown fields.
83
+
84
+ ### Versioning — Semantic Versioning on VCS tags
85
+
86
+ ```
87
+ 1.0.0 ← stable
88
+ v1.0.0 ← also valid
89
+ 1.2.0-RC1
90
+ 2.0.0-beta1
91
+ ```
92
+
93
+ Branches appear as `dev-main`, `dev-feature-x` — for development installs only, not production.
94
+
95
+ ### Requiring WordPress packages
96
+
97
+ WordPress itself is not on Packagist. Use `ext-*` for PHP extensions:
98
+
99
+ ```json
100
+ "require": {
101
+ "php": ">=8.0",
102
+ "ext-json": "*",
103
+ "ext-mbstring": "*"
104
+ }
105
+ ```
106
+
107
+ ---
108
+
109
+ ## 2. PSR-4 Directory Structure
110
+
111
+ ### One class per file. Namespace = directory path. Always.
112
+
113
+ ```
114
+ vendor/package-name/
115
+ ├── composer.json
116
+ └── src/
117
+ ├── Plugin.php → Vendor\Package\Plugin
118
+ ├── Http/
119
+ │ ├── ApiClient.php
120
+ │ ├── HttpClient.php
121
+ │ ├── ApiResponse.php
122
+ │ └── ResponseCache.php
123
+ ├── Pull/
124
+ │ ├── Contracts/
125
+ │ │ └── ImporterInterface.php
126
+ │ ├── Support/
127
+ │ │ ├── ImportResult.php
128
+ │ │ └── Logger.php
129
+ │ ├── ContentImporter.php
130
+ │ └── PullManager.php
131
+ └── WordPress/
132
+ ├── Admin/
133
+ │ ├── SettingsPage.php
134
+ │ └── PullPage.php
135
+ ├── Init/
136
+ │ ├── PostTypeRegistrar.php
137
+ │ └── MetaShortcodes.php
138
+ └── Interaction/
139
+ ├── InteractionController.php
140
+ └── InteractionManager.php
141
+ ```
142
+
143
+ - Class filename matches class name exactly, case-sensitive.
144
+ - Namespace matches directory path from `src/` root exactly.
145
+ - `Plugin.php` at root namespace = the single entry point.
146
+ - No `classmap`. No `files[]`. No bootstrap file.
147
+
148
+ ---
149
+
150
+ ## 3. Strict PHP Typing
151
+
152
+ ### Every file. First line. No exceptions.
153
+
154
+ ```php
155
+ declare(strict_types=1);
156
+
157
+ namespace Vendor\Package\WordPress\Init;
158
+ ```
159
+
160
+ ### All classes `final`. Constructor property promotion.
161
+
162
+ ```php
163
+ final class PostTypeRegistrar
164
+ {
165
+ public function __construct(
166
+ private string $slug,
167
+ private bool $publiclyQueryable = true,
168
+ private ?int $menuPosition = null,
169
+ ) {}
170
+
171
+ public static function make(string $slug): self
172
+ {
173
+ return new self($slug);
174
+ }
175
+ }
176
+ ```
177
+
178
+ ### All methods: parameter types + return types including `void`
179
+
180
+ ```php
181
+ public static function register(): void
182
+ public function import(array $items): ImportResult
183
+ public static function make(): self
184
+ private function buildSlug(string $base): string
185
+ public function getLastResult(): ?ImportResult
186
+ ```
187
+
188
+ ### No docblocks unless the type is a complex array shape PHP cannot express.
189
+
190
+ ### WordPress dynamic return values — handle explicitly, always
191
+
192
+ WP functions return `int|WP_Error`, `array|false`, `WP_Post|null`, etc.
193
+ Never ignore the error branch.
194
+
195
+ ```php
196
+ // RIGHT
197
+ $id = wp_insert_post($args);
198
+ if (is_wp_error($id) || $id === 0) {
199
+ return 0;
200
+ }
201
+ return (int) $id;
202
+ ```
203
+
204
+ ```php
205
+ // RIGHT
206
+ $config = (array) get_option('app_api_settings', []);
207
+ $url = (string) ($config['base_url'] ?? '');
208
+ ```
209
+
210
+ ### WP return type casting reference
211
+
212
+ | WP function / pattern | Safe cast / check |
213
+ |--------------------------------|-----------------------------------------------------|
214
+ | `get_post_meta($id, $k, true)` | `(string)`, `(int)`, `(bool)` per expected type |
215
+ | `get_option()` | `(array)`, `(string)` — always cast, always default |
216
+ | `wp_insert_post()` | `is_wp_error()` check, then `(int)` |
217
+ | `wp_update_post()` | same |
218
+ | `get_posts()` | always `array` — check `!empty()` |
219
+ | `get_comments()` | always `array` |
220
+ | `absint($_POST['id'])` | all incoming integers from request |
221
+ | `sanitize_text_field()` | all incoming strings from request |
222
+ | `apply_filters()` | cast or validate after — return type not guaranteed |
223
+
224
+ ### `apply_filters` — always validate the returned type
225
+
226
+ ```php
227
+ $slug = (string) apply_filters('app_content_slug', 'contents');
228
+
229
+ $items = apply_filters('app_import_items', []);
230
+ if (! is_array($items)) {
231
+ $items = [];
232
+ }
233
+ ```
234
+
235
+ ---
236
+
237
+ ## 4. The Hook Engine
238
+
239
+ ### Two types
240
+
241
+ **Action** — fire and forget. Run code at a point. Return nothing.
242
+ **Filter** — receive a value, return a modified value. Never have side effects.
243
+
244
+ ```
245
+ do_action( 'hook_name', ...$args )
246
+ → runs all callbacks registered with add_action( 'hook_name', $cb, $priority, $args )
247
+
248
+ apply_filters( 'hook_name', $value, ...$args )
249
+ → passes $value through all add_filter callbacks, returns the result
250
+ ```
251
+
252
+ ### Priority
253
+
254
+ Default is `10`. Lower runs earlier. Same priority runs in registration order.
255
+
256
+ ```php
257
+ add_action('init', [PostTypeRegistrar::class, 'register'], 5); // early
258
+ add_action('init', [ContentImporter::class, 'register'], 10); // default
259
+ add_action('init', [MetaShortcodes::class, 'register'], 15); // after
260
+ ```
261
+
262
+ ### `Plugin::init()` — the single entry point
263
+
264
+ ```php
265
+ // packages/vendor/package/src/Plugin.php
266
+ namespace Vendor\Package;
267
+
268
+ final class Plugin
269
+ {
270
+ public static function init(): void
271
+ {
272
+ WordPress\Init\PostTypeRegistrar::register();
273
+ WordPress\Init\MetaShortcodes::register();
274
+ WordPress\Admin\SettingsPage::register();
275
+ WordPress\Interaction\InteractionController::register();
276
+ }
277
+ }
278
+ ```
279
+
280
+ ### Each class registers its own hooks
281
+
282
+ ```php
283
+ namespace Vendor\Package\WordPress\Admin;
284
+
285
+ final class SettingsPage
286
+ {
287
+ public static function register(): void
288
+ {
289
+ add_action('admin_menu', [self::class, 'addMenuPage']);
290
+ add_action('admin_enqueue_scripts', [self::class, 'enqueueAssets']);
291
+ add_action('admin_post_app_save', [self::class, 'handleSave']);
292
+ }
293
+
294
+ public static function addMenuPage(): void { ... }
295
+ public static function enqueueAssets(): void { ... }
296
+ public static function handleSave(): void { ... }
297
+ }
298
+ ```
299
+
300
+ ### Loaded from theme or mu-plugin
301
+
302
+ Use optional `class_exists()` guard so packages are truly optional — if not installed via composer, the theme doesn't break.
303
+
304
+ ```php
305
+ // theme's functions.php or mu-plugin loader
306
+ $autoload = __DIR__ . '/vendor/autoload.php';
307
+ if (file_exists($autoload)) {
308
+ require_once $autoload;
309
+ }
310
+
311
+ if (class_exists(Vendor\Package\Plugin::class)) {
312
+ Vendor\Package\Plugin::init();
313
+ }
314
+ ```
315
+
316
+ ### Rules
317
+
318
+ 1. `add_action` / `add_filter` live **only** inside `register()` methods.
319
+ 2. No closures as hook callbacks unless single-line `static fn()` with zero class dependency.
320
+ 3. No `use ($variable)` closure callbacks.
321
+ 4. Always `[self::class, 'method']` or `[ClassName::class, 'method']` — never string function names for class methods.
322
+ 5. `Plugin::init()` wires. Classes own their hooks. Nothing else.
323
+ 6. No `bootstrap.php`. No `files` autoload. Pure PSR-4.
324
+
325
+ ### Removing hooks
326
+
327
+ ```php
328
+ remove_action('init', [SomeClass::class, 'method']);
329
+ remove_filter('the_content', [SomeClass::class, 'filter'], 10);
330
+
331
+ if (did_action('app_import_complete')) { ... }
332
+ $count = did_filter('app_content_items');
333
+ ```
334
+
335
+ ---
336
+
337
+ ## 5. Naming
338
+
339
+ ### Hook names — package slug prefix, always
340
+
341
+ ```
342
+ {package_slug}_{verb}_{noun} ← actions
343
+ {package_slug}_{noun} ← filters
344
+ ```
345
+
346
+ ```php
347
+ do_action('app_before_import');
348
+ do_action('app_after_import', $result);
349
+ do_action('app_register_importers', $manager);
350
+ do_action('audios_importer_registered', $importer);
351
+ do_action('lms_course_enrolled', $courseId, $userId);
352
+
353
+ apply_filters('app_import_items', $items);
354
+ apply_filters('app_content_slug', 'contents');
355
+ apply_filters('audios_player_args', $args, $postId);
356
+ apply_filters('lms_course_query_args', $queryArgs);
357
+ ```
358
+
359
+ Never use fabricated acronym prefixes. The prefix is the package slug — readable and self-declarative.
360
+
361
+ ### Classes, methods, properties, variables
362
+
363
+ - Classes: `PascalCase` — `PostTypeRegistrar`, `ContentImporter`, `InteractionController`
364
+ - Methods: `camelCase` — `register()`, `handleSave()`, `getLastResult()`
365
+ - Properties: `camelCase` — `$postType`, `$menuSlug`, `$lastResult`
366
+ - Constants: `UPPER_SNAKE_CASE` — `POST_TYPE`, `META_REMOTE_ID`, `OPTION_KEY`
367
+ - Variables: self-declarative, no abbreviations — `$postId` not `$pid`, `$menuSlug` not `$mn`
368
+
369
+ ### Constants for all keys — on the owning class
370
+
371
+ ```php
372
+ final class LegalDocImporter
373
+ {
374
+ public const POST_TYPE = 'page';
375
+ public const META_REMOTE_ID = '_app_legal_remote_id';
376
+ public const META_DOC_TYPE = '_app_legal_doc_type';
377
+ public const OPTION_KEY = 'app_legal_last_sync';
378
+ }
379
+
380
+ update_post_meta($postId, LegalDocImporter::META_REMOTE_ID, $remoteId);
381
+ ```
382
+
383
+ ### Meta key prefix standard
384
+
385
+ Content-type name as prefix. Never a generic plugin abbreviation.
386
+
387
+ | Content type | Meta prefix | Example |
388
+ |--------------|----------------|-------------------------|
389
+ | Legal docs | `_app_legal_` | `_app_legal_remote_id` |
390
+ | Audiobook | `audiobook_` | `audiobook_remote_id` |
391
+ | Audiofile | `audiofile_` | `audiofile_remote_id` |
392
+ | Ebook | `ebook_` | `ebook_remote_id` |
393
+ | Course | `course_` | `course_remote_id` |
394
+
395
+ Leading underscore = hidden from WP custom fields UI. Use for internal/system keys only.
396
+
397
+ **Convention:** Leading `_` (e.g., `_app_legal_`) = hidden/internal meta; no leading underscore (e.g., `audiobook_`) = public/exposed meta.
398
+
399
+ ---
400
+
401
+ ## 6. Posts & Custom Post Types
402
+
403
+ ### Registering CPTs — always on `init`
404
+
405
+ ```php
406
+ namespace Vendor\Package\WordPress\Init;
407
+
408
+ final class PostTypeRegistrar
409
+ {
410
+ public static function register(): void
411
+ {
412
+ add_action('init', [self::class, 'registerTypes']);
413
+ }
414
+
415
+ public static function registerTypes(): void
416
+ {
417
+ $slug = (string) apply_filters('app_content_slug', 'contents');
418
+
419
+ register_post_type('app_content', [
420
+ 'label' => __('Content', 'app'),
421
+ 'public' => true,
422
+ 'show_ui' => false,
423
+ 'show_in_menu' => false,
424
+ 'show_in_rest' => true,
425
+ 'publicly_queryable' => true,
426
+ 'has_archive' => true,
427
+ 'rewrite' => ['slug' => $slug, 'with_front' => false],
428
+ 'supports' => ['title', 'editor', 'excerpt', 'thumbnail'],
429
+ 'hierarchical' => false,
430
+ ]);
431
+ }
432
+ }
433
+ ```
434
+
435
+ Always `apply_filters` on slugs so themes can override. Always `__()` for user-visible strings.
436
+ Never call `register_post_type` outside of an `init` callback.
437
+
438
+ ### Post lifecycle hooks
439
+
440
+ ```php
441
+ add_action('save_post', [self::class, 'onSavePost'], 10, 3);
442
+ add_action('save_post_app_content', [self::class, 'onSaveSpecific'], 10, 2);
443
+ add_action('wp_after_insert_post', [self::class, 'afterInsert'], 10, 4);
444
+ add_action('trashed_post', [self::class, 'onTrashed']);
445
+ add_action('before_delete_post', [self::class, 'beforeDelete']);
446
+ add_action('transition_post_status', [self::class, 'onStatusChange'], 10, 3);
447
+ ```
448
+
449
+ ```php
450
+ public static function onSavePost(int $postId, \WP_Post $post, bool $update): void
451
+ {
452
+ if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
453
+ return;
454
+ }
455
+ if (wp_is_post_revision($postId)) {
456
+ return;
457
+ }
458
+ if (! current_user_can('edit_post', $postId)) {
459
+ return;
460
+ }
461
+ }
462
+ ```
463
+
464
+ ### Query modification — always `pre_get_posts`, never override `$wp_query`
465
+
466
+ ```php
467
+ public static function register(): void
468
+ {
469
+ add_action('pre_get_posts', [self::class, 'modifyArchiveQuery']);
470
+ }
471
+
472
+ public static function modifyArchiveQuery(\WP_Query $query): void
473
+ {
474
+ if (is_admin() || ! $query->is_main_query()) {
475
+ return;
476
+ }
477
+ if (! $query->is_post_type_archive('app_content')) {
478
+ return;
479
+ }
480
+ $query->set('posts_per_page', 24);
481
+ $query->set('orderby', 'title');
482
+ $query->set('order', 'ASC');
483
+ }
484
+ ```
485
+
486
+ ---
487
+
488
+ ## 7. Post Meta
489
+
490
+ ### Reading — always cast, always default
491
+
492
+ ```php
493
+ $remoteId = (int) get_post_meta($postId, ContentImporter::META_REMOTE_ID, true);
494
+ $thumbnailUrl = (string) get_post_meta($postId, ContentImporter::META_THUMBNAIL, true);
495
+ $isActive = (bool) get_post_meta($postId, ContentImporter::META_ACTIVE, true);
496
+ $tags = (array) get_post_meta($postId, ContentImporter::META_TAGS, true) ?: [];
497
+ ```
498
+
499
+ ### Writing — always via WP API, never raw SQL
500
+
501
+ ```php
502
+ update_post_meta($postId, ContentImporter::META_REMOTE_ID, $remoteId);
503
+ update_post_meta($postId, ContentImporter::META_THUMBNAIL, esc_url_raw($thumbnailUrl));
504
+ update_post_meta($postId, ContentImporter::META_DURATION, (int) $duration);
505
+ ```
506
+
507
+ ### Never JSON-encode taxonomy data into postmeta
508
+
509
+ ```php
510
+ // WRONG — JSON in meta causes LIKE queries, full table scans, no WP routing
511
+ update_post_meta($postId, 'content_categories', wp_json_encode($categories));
512
+
513
+ // RIGHT — native WP taxonomy, indexed lookups
514
+ wp_set_object_terms($postId, array_column($categories, 'name'), 'app_content_category');
515
+ ```
516
+
517
+ ---
518
+
519
+ ## 8. Taxonomies
520
+
521
+ ### Registering — always on `init`, after CPTs
522
+
523
+ ```php
524
+ public static function registerTypes(): void
525
+ {
526
+ register_post_type('app_content', [...]);
527
+
528
+ register_taxonomy('app_content_category', ['app_content'], [
529
+ 'label' => __('Categories', 'app'),
530
+ 'public' => false,
531
+ 'show_ui' => false,
532
+ 'show_in_rest' => true,
533
+ 'hierarchical' => true,
534
+ 'rewrite' => false,
535
+ ]);
536
+
537
+ register_taxonomy('app_content_tag', ['app_content'], [
538
+ 'label' => __('Tags', 'app'),
539
+ 'public' => false,
540
+ 'show_ui' => false,
541
+ 'show_in_rest' => true,
542
+ 'hierarchical' => false,
543
+ 'rewrite' => false,
544
+ ]);
545
+ }
546
+ ```
547
+
548
+ ### Writing terms
549
+
550
+ ```php
551
+ wp_set_object_terms($postId, ['Fiction', 'Drama'], 'app_content_category');
552
+ wp_set_object_terms($postId, ['New Tag'], 'app_content_tag', true);
553
+ ```
554
+
555
+ ### Reading terms
556
+
557
+ ```php
558
+ $terms = get_the_terms($postId, 'app_content_category');
559
+ if (! is_array($terms)) {
560
+ $terms = [];
561
+ }
562
+ foreach ($terms as $term) {
563
+ echo esc_html($term->name);
564
+ }
565
+ ```
566
+
567
+ ### Querying by taxonomy — always `tax_query`, never `meta_query LIKE`
568
+
569
+ ```php
570
+ $query = new \WP_Query([
571
+ 'post_type' => 'app_content',
572
+ 'posts_per_page' => 20,
573
+ 'tax_query' => [
574
+ [
575
+ 'taxonomy' => 'app_content_category',
576
+ 'field' => 'slug',
577
+ 'terms' => $categorySlug,
578
+ ],
579
+ ],
580
+ ]);
581
+ ```
582
+
583
+ ### Taxonomy lifecycle hooks
584
+
585
+ ```php
586
+ add_action('create_app_content_category', [self::class, 'onTermCreated'], 10, 2);
587
+ add_action('edited_app_content_category', [self::class, 'onTermUpdated'], 10, 2);
588
+ add_action('delete_app_content_category', [self::class, 'onTermDeleted'], 10, 3);
589
+ ```
590
+
591
+ ---
592
+
593
+ ## 9. Users, Roles & Capabilities
594
+
595
+ ### Reading user data
596
+
597
+ ```php
598
+ $userId = get_current_user_id();
599
+ $user = wp_get_current_user();
600
+ $isSuspended = (bool) get_user_meta($userId, 'is_suspended', true);
601
+ $planLevel = (string) get_user_meta($userId, 'app_plan_level', true);
602
+ ```
603
+
604
+ ### Writing user meta
605
+
606
+ ```php
607
+ update_user_meta($userId, 'app_plan_level', sanitize_text_field($level));
608
+ update_user_meta($userId, 'app_enrolled_at', current_time('mysql'));
609
+ ```
610
+
611
+ ### Capability checks — always before any privileged action
612
+
613
+ ```php
614
+ if (! current_user_can('manage_options')) {
615
+ wp_die(esc_html__('You do not have permission.', 'app'), 403);
616
+ }
617
+
618
+ if (! current_user_can('edit_post', $postId)) {
619
+ return;
620
+ }
621
+
622
+ if (! current_user_can('app_manage_content')) {
623
+ wp_send_json_error(['message' => 'Permission denied.'], 403);
624
+ }
625
+ ```
626
+
627
+ ### Registering custom capabilities
628
+
629
+ ```php
630
+ public static function register(): void
631
+ {
632
+ add_action('init', [self::class, 'addCapabilities']);
633
+ }
634
+
635
+ public static function addCapabilities(): void
636
+ {
637
+ $admin = get_role('administrator');
638
+ if ($admin instanceof \WP_Role) {
639
+ $admin->add_cap('app_manage_content');
640
+ $admin->add_cap('app_view_reports');
641
+ }
642
+ }
643
+ ```
644
+
645
+ ### User lifecycle hooks
646
+
647
+ ```php
648
+ add_action('user_register', [self::class, 'onUserRegistered']);
649
+ add_action('profile_update', [self::class, 'onProfileUpdated'], 10, 3);
650
+ add_action('delete_user', [self::class, 'onUserDeleted']);
651
+ add_action('wp_login', [self::class, 'onLogin'], 10, 2);
652
+ add_action('wp_logout', [self::class, 'onLogout']);
653
+ add_action('set_user_role', [self::class, 'onRoleChanged'], 10, 3);
654
+ ```
655
+
656
+ ---
657
+
658
+ ## 10. Options API
659
+
660
+ ### Reading — always typed default
661
+
662
+ ```php
663
+ $apiKey = (string) get_option('app_api_key', '');
664
+ $config = (array) get_option('app_settings', []);
665
+ $enabled = (bool) get_option('app_feature_enabled', false);
666
+ ```
667
+
668
+ ### Writing — autoload decision matters
669
+
670
+ ```php
671
+ update_option('app_last_sync', current_time('mysql'), false);
672
+ update_option('app_settings', $sanitizedSettings, false);
673
+ update_option('app_api_key', $apiKey, true);
674
+ ```
675
+
676
+ ### Options hooks
677
+
678
+ ```php
679
+ add_action('updated_option', [self::class, 'onOptionUpdated'], 10, 3);
680
+ add_action('update_option_app_api_key', [self::class, 'onApiKeyChanged'], 10, 2);
681
+ add_filter('option_app_settings', [self::class, 'filterSettings']);
682
+ add_filter('default_option_app_settings', [self::class, 'defaultSettings']);
683
+ ```
684
+
685
+ ---
686
+
687
+ ## 11. Custom Database Tables
688
+
689
+ ### Creating
690
+
691
+ ```php
692
+ final class TableInstaller
693
+ {
694
+ private const DB_VERSION_OPTION = 'app_db_version';
695
+
696
+ public static function register(): void
697
+ {
698
+ add_action('init', [self::class, 'maybeInstall']);
699
+ }
700
+
701
+ public static function maybeInstall(): void
702
+ {
703
+ if ((string) get_option(self::DB_VERSION_OPTION, '') === '1.0.0') {
704
+ return;
705
+ }
706
+ self::install();
707
+ }
708
+
709
+ public static function install(): void
710
+ {
711
+ global $wpdb;
712
+
713
+ $charset = $wpdb->get_charset_collate();
714
+
715
+ $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}app_submissions (
716
+ id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
717
+ user_id bigint(20) unsigned NOT NULL DEFAULT 0,
718
+ content_id bigint(20) unsigned NOT NULL DEFAULT 0,
719
+ status varchar(20) NOT NULL DEFAULT 'pending',
720
+ created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
721
+ PRIMARY KEY (id),
722
+ KEY user_id (user_id),
723
+ KEY content_id (content_id)
724
+ ) $charset;";
725
+
726
+ require_once ABSPATH . 'wp-admin/includes/upgrade.php';
727
+ dbDelta($sql);
728
+
729
+ update_option(self::DB_VERSION_OPTION, '1.0.0');
730
+ }
731
+ }
732
+ ```
733
+
734
+ ### Querying — always `$wpdb->prepare()`, no exceptions
735
+
736
+ ```php
737
+ global $wpdb;
738
+
739
+ $rows = $wpdb->get_results(
740
+ $wpdb->prepare(
741
+ "SELECT * FROM {$wpdb->prefix}app_submissions WHERE user_id = %d AND status = %s",
742
+ $userId,
743
+ 'approved'
744
+ )
745
+ );
746
+
747
+ $count = (int) $wpdb->get_var(
748
+ $wpdb->prepare(
749
+ "SELECT COUNT(*) FROM {$wpdb->prefix}app_submissions WHERE content_id = %d",
750
+ $contentId
751
+ )
752
+ );
753
+
754
+ $wpdb->insert(
755
+ $wpdb->prefix . 'app_submissions',
756
+ ['user_id' => $userId, 'content_id' => $contentId, 'status' => 'pending'],
757
+ ['%d', '%d', '%s']
758
+ );
759
+
760
+ $wpdb->update(
761
+ $wpdb->prefix . 'app_submissions',
762
+ ['status' => 'approved'],
763
+ ['id' => $submissionId],
764
+ ['%s'],
765
+ ['%d']
766
+ );
767
+ ```
768
+
769
+ `%d` for integers. `%s` for strings. `%f` for floats. Never concatenate user input into SQL.
770
+
771
+ ---
772
+
773
+ ## 12. Security — The Four-Point Pattern
774
+
775
+ Every form handler, AJAX callback, and REST endpoint follows this order:
776
+
777
+ ```
778
+ 1. Capability check → is this user allowed to do this
779
+ 2. Nonce verification → is this a legitimate request from our own UI
780
+ 3. Sanitize input → clean everything coming in before touching it
781
+ 4. Escape output → clean everything going out before rendering it
782
+ ```
783
+
784
+ Never skip. Never reorder.
785
+
786
+ ### 1. Capability
787
+
788
+ ```php
789
+ if (! current_user_can('edit_posts')) {
790
+ wp_send_json_error(['message' => 'Permission denied.'], 403);
791
+ }
792
+ ```
793
+
794
+ ### 2. Nonce in forms
795
+
796
+ ```php
797
+ wp_nonce_field('app_save_settings', 'app_settings_nonce');
798
+
799
+ if (
800
+ ! isset($_POST['app_settings_nonce']) ||
801
+ ! wp_verify_nonce(
802
+ sanitize_text_field(wp_unslash($_POST['app_settings_nonce'])),
803
+ 'app_save_settings'
804
+ )
805
+ ) {
806
+ wp_die(esc_html__('Security check failed.', 'app'), 403);
807
+ }
808
+ ```
809
+
810
+ ### 2. Nonce in AJAX
811
+
812
+ ```php
813
+ wp_localize_script('app-script', 'appData', [
814
+ 'nonce' => wp_create_nonce('app_ajax_action'),
815
+ 'ajaxUrl' => admin_url('admin-ajax.php'),
816
+ ]);
817
+
818
+ check_ajax_referer('app_ajax_action', 'nonce');
819
+ ```
820
+
821
+ ### 3. Sanitize — by type
822
+
823
+ ```php
824
+ $title = sanitize_text_field(wp_unslash($_POST['title'] ?? ''));
825
+ $email = sanitize_email(wp_unslash($_POST['email'] ?? ''));
826
+ $url = esc_url_raw(wp_unslash($_POST['url'] ?? ''));
827
+ $postId = absint($_POST['post_id'] ?? 0);
828
+ $content = wp_kses_post(wp_unslash($_POST['content'] ?? ''));
829
+ $textarea = sanitize_textarea_field(wp_unslash($_POST['body'] ?? ''));
830
+ $slug = sanitize_title(wp_unslash($_POST['slug'] ?? ''));
831
+ $key = sanitize_key(wp_unslash($_POST['key'] ?? ''));
832
+ ```
833
+
834
+ `wp_unslash` first, then sanitize. Always.
835
+
836
+ ### 4. Escape — by output context
837
+
838
+ ```php
839
+ echo esc_html($title); // text content
840
+ echo '<div class="' . esc_attr($cssClass) . '">'; // attribute
841
+ echo '<a href="' . esc_url($permalink) . '">'; // URL in HTML
842
+ echo 'var x = ' . wp_json_encode($data) . ';'; // JS variable
843
+ echo wp_kses($richContent, ['strong' => [], 'em' => [], 'a' => ['href' => []]]);
844
+
845
+ wp_safe_redirect(esc_url_raw($redirectUrl)); // redirect
846
+ ```
847
+
848
+ Escape at the point of output, not when building the variable. Once. Not twice.
849
+
850
+ ---
851
+
852
+ ## 13. AJAX
853
+
854
+ ### Registering handlers
855
+
856
+ ```php
857
+ public static function register(): void
858
+ {
859
+ add_action('wp_ajax_app_save_item', [self::class, 'handleSaveItem']);
860
+ add_action('wp_ajax_nopriv_app_public', [self::class, 'handlePublicData']);
861
+ }
862
+ ```
863
+
864
+ Add `nopriv` only when the action is genuinely available to logged-out users.
865
+
866
+ ### Complete handler
867
+
868
+ ```php
869
+ public static function handleSaveItem(): void
870
+ {
871
+ if (! current_user_can('edit_posts')) {
872
+ wp_send_json_error(['message' => 'Permission denied.'], 403);
873
+ }
874
+
875
+ check_ajax_referer('app_save_item', 'nonce');
876
+
877
+ $postId = absint($_POST['post_id'] ?? 0);
878
+ $title = sanitize_text_field(wp_unslash($_POST['title'] ?? ''));
879
+
880
+ if (! $postId || ! $title) {
881
+ wp_send_json_error(['message' => 'Invalid input.'], 400);
882
+ }
883
+
884
+ $result = self::saveItem($postId, $title);
885
+
886
+ wp_send_json_success([
887
+ 'id' => $result,
888
+ 'title' => esc_html($title),
889
+ ]);
890
+ }
891
+ ```
892
+
893
+ ### admin-post.php — for non-AJAX form submissions
894
+
895
+ ```php
896
+ public static function register(): void
897
+ {
898
+ add_action('admin_post_app_enroll', [self::class, 'handleEnrollment']);
899
+ }
900
+
901
+ public static function handleEnrollment(): void
902
+ {
903
+ if (! is_user_logged_in()) {
904
+ wp_die(esc_html__('You must be logged in.', 'app'), 403);
905
+ }
906
+
907
+ $courseId = absint($_POST['course_id'] ?? 0);
908
+ $nonceValue = sanitize_text_field(wp_unslash($_POST['app_enroll_nonce'] ?? ''));
909
+
910
+ if (! wp_verify_nonce($nonceValue, 'app_enroll_' . $courseId)) {
911
+ wp_die(esc_html__('Security check failed.', 'app'), 403);
912
+ }
913
+
914
+ self::enroll($courseId, get_current_user_id());
915
+ wp_safe_redirect(get_permalink($courseId));
916
+ exit;
917
+ }
918
+ ```
919
+
920
+ ---
921
+
922
+ ## 14. REST API
923
+
924
+ ### Registering endpoints
925
+
926
+ ```php
927
+ public static function register(): void
928
+ {
929
+ add_action('rest_api_init', [self::class, 'registerRoutes']);
930
+ }
931
+
932
+ public static function registerRoutes(): void
933
+ {
934
+ register_rest_route('app/v1', '/content/(?P<id>\d+)', [
935
+ 'methods' => \WP_REST_Server::READABLE,
936
+ 'callback' => [self::class, 'getContent'],
937
+ 'permission_callback' => [self::class, 'permissionCheck'],
938
+ 'args' => [
939
+ 'id' => [
940
+ 'validate_callback' => static fn($value): bool => is_numeric($value),
941
+ 'sanitize_callback' => 'absint',
942
+ 'required' => true,
943
+ ],
944
+ ],
945
+ ]);
946
+
947
+ register_rest_route('app/v1', '/content', [
948
+ 'methods' => \WP_REST_Server::CREATABLE,
949
+ 'callback' => [self::class, 'createContent'],
950
+ 'permission_callback' => static fn(): bool => current_user_can('edit_posts'),
951
+ ]);
952
+ }
953
+
954
+ public static function permissionCheck(\WP_REST_Request $request): bool
955
+ {
956
+ return current_user_can('read');
957
+ }
958
+
959
+ public static function getContent(\WP_REST_Request $request): \WP_REST_Response
960
+ {
961
+ $id = (int) $request->get_param('id');
962
+ $post = get_post($id);
963
+
964
+ if (! $post instanceof \WP_Post || $post->post_type !== 'app_content') {
965
+ return new \WP_REST_Response(['message' => 'Not found.'], 404);
966
+ }
967
+
968
+ return new \WP_REST_Response([
969
+ 'id' => $post->ID,
970
+ 'title' => esc_html($post->post_title),
971
+ 'slug' => $post->post_name,
972
+ ], 200);
973
+ }
974
+ ```
975
+
976
+ ### Add fields to existing REST responses
977
+
978
+ ```php
979
+ add_action('rest_api_init', static function (): void {
980
+ register_rest_field('post', 'app_meta', [
981
+ 'get_callback' => static fn(array $post): array => [
982
+ 'remote_id' => (int) get_post_meta($post['id'], '_app_remote_id', true),
983
+ ],
984
+ 'update_callback' => null,
985
+ 'schema' => ['type' => 'object', 'description' => 'App metadata'],
986
+ ]);
987
+ });
988
+ ```
989
+
990
+ ### Filter REST query args
991
+
992
+ ```php
993
+ add_filter('rest_app_content_query', [self::class, 'filterRestQuery'], 10, 2);
994
+
995
+ public static function filterRestQuery(array $args, \WP_REST_Request $request): array
996
+ {
997
+ $args['meta_key'] = '_app_featured';
998
+ $args['meta_value'] = '1';
999
+ return $args;
1000
+ }
1001
+ ```
1002
+
1003
+ ### REST auth — Application Passwords
1004
+
1005
+ ```php
1006
+ add_filter('rest_authentication_errors', [self::class, 'checkAuth']);
1007
+
1008
+ public static function checkAuth(mixed $result): mixed
1009
+ {
1010
+ if (! is_null($result)) {
1011
+ return $result;
1012
+ }
1013
+ if (! is_user_logged_in()) {
1014
+ return new \WP_Error('rest_not_logged_in', 'Authentication required.', ['status' => 401]);
1015
+ }
1016
+ return $result;
1017
+ }
1018
+ ```
1019
+
1020
+ ---
1021
+
1022
+ ## 15. Remote HTTP
1023
+
1024
+ Never use `file_get_contents` or `curl` directly. Always use the WP HTTP API.
1025
+
1026
+ ### GET
1027
+
1028
+ ```php
1029
+ $response = wp_remote_get('https://api.example.com/v1/content', [
1030
+ 'timeout' => 15,
1031
+ 'headers' => [
1032
+ 'Authorization' => 'Bearer ' . $apiKey,
1033
+ 'Accept' => 'application/json',
1034
+ ],
1035
+ ]);
1036
+
1037
+ if (is_wp_error($response)) {
1038
+ throw new \RuntimeException('HTTP request failed: ' . $response->get_error_message());
1039
+ }
1040
+
1041
+ $statusCode = (int) wp_remote_retrieve_response_code($response);
1042
+ $body = wp_remote_retrieve_body($response);
1043
+
1044
+ if ($statusCode !== 200) {
1045
+ throw new \RuntimeException("API returned HTTP {$statusCode}");
1046
+ }
1047
+
1048
+ $data = json_decode($body, true);
1049
+ if (! is_array($data)) {
1050
+ throw new \RuntimeException('Invalid JSON response from API.');
1051
+ }
1052
+ ```
1053
+
1054
+ ### POST
1055
+
1056
+ ```php
1057
+ $response = wp_remote_post('https://api.example.com/v1/notify', [
1058
+ 'timeout' => 10,
1059
+ 'headers' => ['Content-Type' => 'application/json'],
1060
+ 'body' => wp_json_encode(['event' => 'enrolled', 'user_id' => $userId]),
1061
+ 'data_format' => 'body',
1062
+ ]);
1063
+ ```
1064
+
1065
+ ### Caching API responses
1066
+
1067
+ ```php
1068
+ private function fetchWithCache(string $url): array
1069
+ {
1070
+ $cacheKey = 'app_api_' . md5($url);
1071
+ $cached = get_transient($cacheKey);
1072
+
1073
+ if (is_array($cached)) {
1074
+ return $cached;
1075
+ }
1076
+
1077
+ $response = wp_remote_get($url, ['timeout' => 15]);
1078
+
1079
+ if (is_wp_error($response)) {
1080
+ return [];
1081
+ }
1082
+
1083
+ $data = json_decode(wp_remote_retrieve_body($response), true);
1084
+ if (! is_array($data)) {
1085
+ return [];
1086
+ }
1087
+
1088
+ set_transient($cacheKey, $data, HOUR_IN_SECONDS);
1089
+ return $data;
1090
+ }
1091
+ ```
1092
+
1093
+ ### Filter outbound requests
1094
+
1095
+ ```php
1096
+ add_filter('http_request_args', [self::class, 'filterHttpArgs'], 10, 2);
1097
+
1098
+ public static function filterHttpArgs(array $args, string $url): array
1099
+ {
1100
+ $args['user-agent'] = 'AppName/1.0 (+https://example.com)';
1101
+ return $args;
1102
+ }
1103
+ ```
1104
+
1105
+ ---
1106
+
1107
+ ## 16. Logging & WP-CLI
1108
+
1109
+ ### Conditional error_log
1110
+
1111
+ ```php
1112
+ private function log(string $message, string $level = 'info'): void
1113
+ {
1114
+ if (! defined('WP_DEBUG') || ! WP_DEBUG) {
1115
+ return;
1116
+ }
1117
+ error_log('[app][' . strtoupper($level) . '] ' . $message);
1118
+ }
1119
+ ```
1120
+
1121
+ ### WP-CLI
1122
+
1123
+ ```php
1124
+ public static function register(): void
1125
+ {
1126
+ if (defined('WP_CLI') && WP_CLI) {
1127
+ \WP_CLI::add_command('app import', [self::class, 'cliImport']);
1128
+ }
1129
+ }
1130
+
1131
+ public static function cliImport(array $args, array $assocArgs): void
1132
+ {
1133
+ $force = isset($assocArgs['force']);
1134
+ \WP_CLI::log('Starting import...');
1135
+ $result = (new ImportManager())->run($force);
1136
+ \WP_CLI::success("Imported {$result->importedCount()} items.");
1137
+ }
1138
+ ```
1139
+
1140
+ ---
1141
+
1142
+ ## 17. Scheduling
1143
+
1144
+ ```php
1145
+ public static function register(): void
1146
+ {
1147
+ add_action('app_scheduled_sync', [self::class, 'runSync']);
1148
+ add_filter('cron_schedules', [self::class, 'addSchedule']);
1149
+ add_action('init', [self::class, 'scheduleEvents']);
1150
+ }
1151
+
1152
+ public static function addSchedule(array $schedules): array
1153
+ {
1154
+ $schedules['app_every_6_hours'] = [
1155
+ 'interval' => 6 * HOUR_IN_SECONDS,
1156
+ 'display' => __('Every 6 hours', 'app'),
1157
+ ];
1158
+ return $schedules;
1159
+ }
1160
+
1161
+ public static function scheduleEvents(): void
1162
+ {
1163
+ if (! wp_next_scheduled('app_scheduled_sync')) {
1164
+ wp_schedule_event(time(), 'app_every_6_hours', 'app_scheduled_sync');
1165
+ }
1166
+ }
1167
+ ```
1168
+
1169
+ > **Note for libraries:** For Composer packages loaded via theme/mu-plugin, cron cleanup must be handled by the consumer (e.g., theme deactivation hook), not via `register_deactivation_hook`.
1170
+
1171
+ ---
1172
+
1173
+ ## 18. Hook Bus — Inter-Package Extension
1174
+
1175
+ When an addon needs to extend a base package, use a WP action. Never direct class calls across package boundaries.
1176
+
1177
+ ### Base package fires the extension point
1178
+
1179
+ ```php
1180
+ // In PullManager::run()
1181
+ do_action('app_register_importers', $this);
1182
+
1183
+ // In PostTypeRegistrar::registerTypes()
1184
+ do_action('app_register_post_types');
1185
+ ```
1186
+
1187
+ ### Addon registers in a dedicated class, not directly in Plugin::init()
1188
+
1189
+ Each addon creates a dedicated registrar class that owns the `add_action` calls. `Plugin::init()` stays clean — just `ClassName::register()` wiring.
1190
+
1191
+ ```php
1192
+ // audios-addon/src/WordPress/Init/ImporterRegistrar.php
1193
+ namespace Vendor\Audios\WordPress\Init;
1194
+
1195
+ final class ImporterRegistrar
1196
+ {
1197
+ public static function register(): void
1198
+ {
1199
+ add_action('app_register_importers', [self::class, 'onRegisterImporters']);
1200
+ add_action('app_register_post_types', [AudioCptRegistrar::class, 'registerTypes']);
1201
+ }
1202
+
1203
+ public static function onRegisterImporters($manager): void
1204
+ {
1205
+ $manager->addImporter(
1206
+ new \Vendor\Audios\Pull\AudiobookImporter(),
1207
+ $manager->getClient()->getAudiobooks()
1208
+ );
1209
+ $manager->addImporter(
1210
+ new \Vendor\Audios\Pull\AudiofileImporter(),
1211
+ $manager->getClient()->getAudiofiles()
1212
+ );
1213
+ }
1214
+ }
1215
+ ```
1216
+
1217
+ ```php
1218
+ // audios-addon/src/Plugin.php — stays clean
1219
+ namespace Vendor\Audios;
1220
+
1221
+ final class Plugin
1222
+ {
1223
+ public static function init(): void
1224
+ {
1225
+ WordPress\Init\ImporterRegistrar::register();
1226
+ }
1227
+ }
1228
+ ```
1229
+
1230
+ No closures as hook callbacks. No `use` in Plugin.php. No bootstrap.php.
1231
+ No `files` autoload. `Plugin::init()` is the only entry point — pure `ClassName::register()` wiring.
1232
+
1233
+ Base knows nothing about addons. Addons know the base. Zero upward coupling. Adding a new addon means adding a new `register()` call inside `Plugin::init()` and a new registrar class — nothing else changes.
1234
+
1235
+ ---
1236
+
1237
+ ## 19. Template Integration
1238
+
1239
+ Packages never render HTML directly. They provide data via manager classes. Templates consume it.
1240
+
1241
+ ```php
1242
+ $meta = ContentManager::getMeta(get_the_ID());
1243
+ ?>
1244
+ <h1><?php echo esc_html(get_the_title()); ?></h1>
1245
+ <img src="<?php echo esc_url($meta['thumbnail']); ?>" alt="<?php echo esc_attr(get_the_title()); ?>">
1246
+ <p><?php echo esc_html($meta['excerpt']); ?></p>
1247
+ ```
1248
+
1249
+ ### Expose a filter so themes can override data before render
1250
+
1251
+ ```php
1252
+ final class ContentManager
1253
+ {
1254
+ public static function getMeta(int $postId): array
1255
+ {
1256
+ $meta = [
1257
+ 'thumbnail' => (string) get_post_meta($postId, ContentImporter::META_THUMBNAIL, true),
1258
+ 'excerpt' => (string) get_post_meta($postId, ContentImporter::META_EXCERPT, true),
1259
+ ];
1260
+
1261
+ return (array) apply_filters('app_content_meta', $meta, $postId);
1262
+ }
1263
+ }
1264
+ ```
1265
+
1266
+ ---
1267
+
1268
+ ## 20. Pre-Commit Checklist
1269
+
1270
+ - [ ] `declare(strict_types=1)` on every file
1271
+ - [ ] Namespace matches directory path exactly
1272
+ - [ ] All classes `final`
1273
+ - [ ] Constructor property promotion with `private readonly`
1274
+ - [ ] All methods typed — parameters + return types including `void`
1275
+ - [ ] `add_action` / `add_filter` only inside `register()` methods
1276
+ - [ ] `Plugin::init()` is the single entry point — no bootstrap.php, no files autoload
1277
+ - [ ] No `use` in Plugin.php
1278
+ - [ ] All meta/option/post-type keys defined as `public const` on the owning class
1279
+ - [ ] `is_wp_error()` checked on every `wp_insert_post`, `wp_update_post`
1280
+ - [ ] Four-point security pattern (capability → nonce → sanitize → escape)
1281
+ - [ ] `wp_unslash` before `sanitize_*` on all `$_POST`/`$_GET` reads
1282
+ - [ ] All output escaped at point of `echo`
1283
+ - [ ] All SQL through `$wpdb->prepare()` — zero concatenation
1284
+ - [ ] No taxonomy data JSON-encoded into postmeta
1285
+ - [ ] Hook names prefixed with package slug — no acronyms
1286
+ - [ ] Variable names self-declarative — no abbreviations
1287
+ - [ ] `composer.json` has no `"version"` field
1288
+
1289
+ ---
1290
+
1291
+ ## 21. Reference Example — eCommerce Package
1292
+
1293
+ ### Package layout
1294
+
1295
+ ```
1296
+ acme/ecommerce/
1297
+ ├── composer.json
1298
+ └── src/
1299
+ ├── Plugin.php
1300
+ ├── Order/
1301
+ │ ├── OrderManager.php
1302
+ │ └── OrderStatus.php
1303
+ ├── Product/
1304
+ │ └── ProductManager.php
1305
+ └── WordPress/
1306
+ ├── Admin/
1307
+ │ └── OrdersPage.php
1308
+ ├── Ajax/
1309
+ │ └── CartController.php
1310
+ ├── Init/
1311
+ │ ├── PostTypeRegistrar.php
1312
+ │ └── TableInstaller.php
1313
+ └── Rest/
1314
+ └── OrderEndpoint.php
1315
+ ```
1316
+
1317
+ ### `composer.json`
1318
+
1319
+ ```json
1320
+ {
1321
+ "name": "acme/ecommerce",
1322
+ "type": "library",
1323
+ "description": "Headless eCommerce engine for WordPress.",
1324
+ "require": {
1325
+ "php": ">=8.0"
1326
+ },
1327
+ "autoload": {
1328
+ "psr-4": {
1329
+ "Acme\\Ecommerce\\": "src/"
1330
+ }
1331
+ }
1332
+ }
1333
+ ```
1334
+
1335
+ ### `src/Plugin.php`
1336
+
1337
+ ```php
1338
+ declare(strict_types=1);
1339
+
1340
+ namespace Acme\Ecommerce;
1341
+
1342
+ final class Plugin
1343
+ {
1344
+ public static function init(): void
1345
+ {
1346
+ WordPress\Init\TableInstaller::register();
1347
+ WordPress\Init\PostTypeRegistrar::register();
1348
+ WordPress\Admin\OrdersPage::register();
1349
+ WordPress\Ajax\CartController::register();
1350
+ WordPress\Rest\OrderEndpoint::register();
1351
+ }
1352
+ }
1353
+ ```
1354
+
1355
+ No logic. No `use`. Just `ClassName::register()` calls.
1356
+
1357
+ ### `src/WordPress/Init/PostTypeRegistrar.php`
1358
+
1359
+ ```php
1360
+ declare(strict_types=1);
1361
+
1362
+ namespace Acme\Ecommerce\WordPress\Init;
1363
+
1364
+ final class PostTypeRegistrar
1365
+ {
1366
+ public const POST_TYPE_PRODUCT = 'product';
1367
+ public const POST_TYPE_ORDER = 'order';
1368
+
1369
+ public static function register(): void
1370
+ {
1371
+ add_action('init', [self::class, 'registerTypes'], 5);
1372
+ }
1373
+
1374
+ public static function registerTypes(): void
1375
+ {
1376
+ register_post_type(self::POST_TYPE_PRODUCT, [
1377
+ 'label' => __('Products', 'acme-shop'),
1378
+ 'public' => true,
1379
+ 'show_ui' => true,
1380
+ 'show_in_rest' => true,
1381
+ 'publicly_queryable' => true,
1382
+ 'has_archive' => true,
1383
+ 'rewrite' => [
1384
+ 'slug' => (string) apply_filters('product_slug', 'products'),
1385
+ 'with_front' => false,
1386
+ ],
1387
+ 'supports' => ['title', 'editor', 'thumbnail', 'excerpt'],
1388
+ ]);
1389
+
1390
+ register_post_type(self::POST_TYPE_ORDER, [
1391
+ 'label' => __('Orders', 'acme-shop'),
1392
+ 'public' => false,
1393
+ 'show_ui' => true,
1394
+ 'show_in_menu' => false,
1395
+ 'show_in_rest' => false,
1396
+ 'publicly_queryable' => false,
1397
+ 'supports' => ['title'],
1398
+ ]);
1399
+
1400
+ register_taxonomy('product_category', [self::POST_TYPE_PRODUCT], [
1401
+ 'label' => __('Categories', 'acme-shop'),
1402
+ 'public' => true,
1403
+ 'show_in_rest' => true,
1404
+ 'hierarchical' => true,
1405
+ 'rewrite' => ['slug' => 'product-category'],
1406
+ ]);
1407
+
1408
+ do_action('register_post_types');
1409
+ }
1410
+ }
1411
+ ```
1412
+
1413
+ ### `src/Order/OrderStatus.php`
1414
+
1415
+ ```php
1416
+ declare(strict_types=1);
1417
+
1418
+ namespace Acme\Ecommerce\Order;
1419
+
1420
+ final class OrderStatus
1421
+ {
1422
+ public const PENDING = 'pending';
1423
+ public const PROCESSING = 'processing';
1424
+ public const COMPLETE = 'complete';
1425
+ public const CANCELLED = 'cancelled';
1426
+
1427
+ public const META_TOTAL = '_total';
1428
+ public const META_CUSTOMER = '_customer_id';
1429
+ public const META_LINE_ITEMS = '_line_items';
1430
+ }
1431
+ ```
1432
+
1433
+ ### `src/Pull/PullManagerInterface.php`
1434
+
1435
+ ```php
1436
+ declare(strict_types=1);
1437
+
1438
+ namespace Acme\Ecommerce\Pull;
1439
+
1440
+ interface PullManagerInterface
1441
+ {
1442
+ public function addImporter(ImporterInterface $importer, iterable $items): void;
1443
+ public function getClient(): ClientInterface;
1444
+ }
1445
+ ```
1446
+
1447
+ ### `src/Pull/ImporterInterface.php`
1448
+
1449
+ ```php
1450
+ declare(strict_types=1);
1451
+
1452
+ namespace Acme\Ecommerce\Pull;
1453
+
1454
+ interface ImporterInterface
1455
+ {
1456
+ public function import(iterable $items): ImportResult;
1457
+ }
1458
+ ```
1459
+
1460
+ ### `src/Pull/ImportResult.php`
1461
+
1462
+ ```php
1463
+ declare(strict_types=1);
1464
+
1465
+ namespace Acme\Ecommerce\Pull;
1466
+
1467
+ final class ImportResult
1468
+ {
1469
+ public function __construct(
1470
+ public readonly int $importedCount,
1471
+ public readonly int $failedCount,
1472
+ public readonly array $errors = [],
1473
+ ) {}
1474
+ }
1475
+ ```
1476
+
1477
+ ### `src/Pull/ClientInterface.php`
1478
+
1479
+ ```php
1480
+ declare(strict_types=1);
1481
+
1482
+ namespace Acme\Ecommerce\Pull;
1483
+
1484
+ interface ClientInterface
1485
+ {
1486
+ public function getProducts(): iterable;
1487
+ public function getOrders(): iterable;
1488
+ }
1489
+ ```
1490
+
1491
+ ### `src/Order/OrderManager.php`
1492
+
1493
+ ```php
1494
+ declare(strict_types=1);
1495
+
1496
+ namespace Acme\Ecommerce\Order;
1497
+
1498
+ final class OrderManager
1499
+ {
1500
+ public function __construct(
1501
+ private readonly \wpdb $wpdb,
1502
+ ) {}
1503
+
1504
+ public function create(int $customerId, array $lineItems): int
1505
+ {
1506
+ $total = array_sum(array_column($lineItems, 'price'));
1507
+
1508
+ $postId = wp_insert_post([
1509
+ 'post_type' => 'order',
1510
+ 'post_title' => 'Order — ' . current_time('mysql'),
1511
+ 'post_status' => OrderStatus::PENDING,
1512
+ ]);
1513
+
1514
+ if (is_wp_error($postId) || $postId === 0) {
1515
+ return 0;
1516
+ }
1517
+
1518
+ update_post_meta($postId, OrderStatus::META_CUSTOMER, $customerId);
1519
+ update_post_meta($postId, OrderStatus::META_TOTAL, $total);
1520
+ update_post_meta($postId, OrderStatus::META_LINE_ITEMS, $lineItems);
1521
+
1522
+ do_action('order_created', $postId, $customerId, $lineItems);
1523
+
1524
+ return $postId;
1525
+ }
1526
+
1527
+ public function transition(int $orderId, string $newStatus): void
1528
+ {
1529
+ $previous = get_post_status($orderId);
1530
+
1531
+ wp_update_post([
1532
+ 'ID' => $orderId,
1533
+ 'post_status' => $newStatus,
1534
+ ]);
1535
+
1536
+ do_action('order_status_changed', $orderId, $previous, $newStatus);
1537
+
1538
+ if ($newStatus === OrderStatus::COMPLETE) {
1539
+ do_action('order_completed', $orderId);
1540
+ }
1541
+ }
1542
+
1543
+ public function getTotal(int $orderId): float
1544
+ {
1545
+ return (float) get_post_meta($orderId, OrderStatus::META_TOTAL, true);
1546
+ }
1547
+
1548
+ public function getLineItems(int $orderId): array
1549
+ {
1550
+ return (array) get_post_meta($orderId, OrderStatus::META_LINE_ITEMS, true) ?: [];
1551
+ }
1552
+ }
1553
+ ```
1554
+
1555
+ ### `src/WordPress/Ajax/CartController.php`
1556
+
1557
+ ```php
1558
+ declare(strict_types=1);
1559
+
1560
+ namespace Acme\Ecommerce\WordPress\Ajax;
1561
+
1562
+ use Acme\Ecommerce\Order\OrderManager;
1563
+
1564
+ final class CartController
1565
+ {
1566
+ public static function register(): void
1567
+ {
1568
+ add_action('wp_ajax_ec_place_order', [self::class, 'handlePlaceOrder']);
1569
+ add_action('wp_ajax_nopriv_ec_place_order', [self::class, 'handlePlaceOrder']);
1570
+ }
1571
+
1572
+ public static function handlePlaceOrder(): void
1573
+ {
1574
+ check_ajax_referer('place_order', 'nonce');
1575
+
1576
+ global $wpdb;
1577
+
1578
+ $customerId = get_current_user_id();
1579
+ $rawItems = $_POST['line_items'] ?? [];
1580
+
1581
+ if (! is_array($rawItems) || empty($rawItems)) {
1582
+ wp_send_json_error(['message' => 'No items in order.'], 400);
1583
+ }
1584
+
1585
+ $lineItems = array_map(static function (array $item): array {
1586
+ return [
1587
+ 'product_id' => absint($item['product_id'] ?? 0),
1588
+ 'qty' => absint($item['qty'] ?? 1),
1589
+ 'price' => (float) ($item['price'] ?? 0.0),
1590
+ ];
1591
+ }, $rawItems);
1592
+
1593
+ $orderId = (new OrderManager($wpdb))->create($customerId, $lineItems);
1594
+
1595
+ if (! $orderId) {
1596
+ wp_send_json_error(['message' => 'Could not create order.'], 500);
1597
+ }
1598
+
1599
+ wp_send_json_success(['order_id' => $orderId]);
1600
+ }
1601
+ }
1602
+ ```
1603
+
1604
+ ### `src/WordPress/Rest/OrderEndpoint.php`
1605
+
1606
+ ```php
1607
+ declare(strict_types=1);
1608
+
1609
+ namespace Acme\Ecommerce\WordPress\Rest;
1610
+
1611
+ use Acme\Ecommerce\Order\OrderManager;
1612
+ use Acme\Ecommerce\Order\OrderStatus;
1613
+
1614
+ final class OrderEndpoint
1615
+ {
1616
+ public static function register(): void
1617
+ {
1618
+ add_action('rest_api_init', [self::class, 'registerRoutes']);
1619
+ }
1620
+
1621
+ public static function registerRoutes(): void
1622
+ {
1623
+ register_rest_route('v1', '/orders/(?P<id>\d+)', [
1624
+ 'methods' => \WP_REST_Server::READABLE,
1625
+ 'callback' => [self::class, 'getOrder'],
1626
+ 'permission_callback' => [self::class, 'permissionCheck'],
1627
+ 'args' => [
1628
+ 'id' => [
1629
+ 'sanitize_callback' => 'absint',
1630
+ 'validate_callback' => static fn($v): bool => is_numeric($v) && $v > 0,
1631
+ 'required' => true,
1632
+ ],
1633
+ ],
1634
+ ]);
1635
+
1636
+ register_rest_route('v1', '/orders/(?P<id>\d+)/complete', [
1637
+ 'methods' => \WP_REST_Server::EDITABLE,
1638
+ 'callback' => [self::class, 'completeOrder'],
1639
+ 'permission_callback' => static fn(): bool => current_user_can('manage_options'),
1640
+ ]);
1641
+ }
1642
+
1643
+ public static function permissionCheck(\WP_REST_Request $request): bool
1644
+ {
1645
+ $orderId = (int) $request->get_param('id');
1646
+ $customerId = (int) get_post_meta($orderId, OrderStatus::META_CUSTOMER, true);
1647
+
1648
+ return get_current_user_id() === $customerId || current_user_can('manage_options');
1649
+ }
1650
+
1651
+ public static function getOrder(\WP_REST_Request $request): \WP_REST_Response
1652
+ {
1653
+ $orderId = (int) $request->get_param('id');
1654
+ $post = get_post($orderId);
1655
+
1656
+ if (! $post instanceof \WP_Post || $post->post_type !== 'order') {
1657
+ return new \WP_REST_Response(['message' => 'Order not found.'], 404);
1658
+ }
1659
+
1660
+ global $wpdb;
1661
+ $manager = new OrderManager($wpdb);
1662
+
1663
+ return new \WP_REST_Response([
1664
+ 'id' => $post->ID,
1665
+ 'status' => $post->post_status,
1666
+ 'total' => $manager->getTotal($orderId),
1667
+ 'line_items' => $manager->getLineItems($orderId),
1668
+ ], 200);
1669
+ }
1670
+
1671
+ public static function completeOrder(\WP_REST_Request $request): \WP_REST_Response
1672
+ {
1673
+ $orderId = (int) $request->get_param('id');
1674
+ $post = get_post($orderId);
1675
+
1676
+ if (! $post instanceof \WP_Post || $post->post_type !== 'order') {
1677
+ return new \WP_REST_Response(['message' => 'Order not found.'], 404);
1678
+ }
1679
+
1680
+ global $wpdb;
1681
+ (new OrderManager($wpdb))->transition($orderId, OrderStatus::COMPLETE);
1682
+
1683
+ return new \WP_REST_Response(['id' => $orderId, 'status' => OrderStatus::COMPLETE], 200);
1684
+ }
1685
+ }
1686
+ ```
1687
+
1688
+ ### `src/WordPress/Admin/OrdersPage.php`
1689
+
1690
+ ```php
1691
+ declare(strict_types=1);
1692
+
1693
+ namespace Acme\Ecommerce\WordPress\Admin;
1694
+
1695
+ use Acme\Ecommerce\Order\OrderStatus;
1696
+
1697
+ final class OrdersPage
1698
+ {
1699
+ public static function register(): void
1700
+ {
1701
+ add_action('admin_menu', [self::class, 'addMenuPage']);
1702
+ add_action('admin_post_update_order_status', [self::class, 'handleStatusUpdate']);
1703
+ }
1704
+
1705
+ public static function addMenuPage(): void
1706
+ {
1707
+ add_menu_page(
1708
+ __('Orders', 'acme-shop'),
1709
+ __('Orders', 'acme-shop'),
1710
+ 'manage_options',
1711
+ 'orders',
1712
+ [self::class, 'renderPage'],
1713
+ 'dashicons-cart',
1714
+ 56
1715
+ );
1716
+ }
1717
+
1718
+ public static function renderPage(): void
1719
+ {
1720
+ if (! current_user_can('manage_options')) {
1721
+ wp_die(esc_html__('Permission denied.', 'acme-shop'), 403);
1722
+ }
1723
+
1724
+ global $wpdb;
1725
+
1726
+ $orders = $wpdb->get_results(
1727
+ $wpdb->prepare(
1728
+ "SELECT ID, post_title, post_status FROM {$wpdb->posts}
1729
+ WHERE post_type = %s ORDER BY post_date DESC LIMIT %d",
1730
+ 'order',
1731
+ 50
1732
+ )
1733
+ );
1734
+
1735
+ echo '<div class="wrap"><h1>' . esc_html__('Orders', 'acme-shop') . '</h1><table class="widefat"><tbody>';
1736
+
1737
+ foreach ($orders as $order) {
1738
+ $total = (float) get_post_meta((int) $order->ID, OrderStatus::META_TOTAL, true);
1739
+ echo '<tr>';
1740
+ echo '<td>' . esc_html($order->post_title) . '</td>';
1741
+ echo '<td>' . esc_html($order->post_status) . '</td>';
1742
+ echo '<td>' . esc_html(number_format($total, 2)) . '</td>';
1743
+ echo '</tr>';
1744
+ }
1745
+
1746
+ echo '</tbody></table></div>';
1747
+ }
1748
+
1749
+ public static function handleStatusUpdate(): void
1750
+ {
1751
+ if (! current_user_can('manage_options')) {
1752
+ wp_die(esc_html__('Permission denied.', 'acme-shop'), 403);
1753
+ }
1754
+
1755
+ $nonceValue = sanitize_text_field(wp_unslash($_POST['order_nonce'] ?? ''));
1756
+ $orderId = absint($_POST['order_id'] ?? 0);
1757
+ $newStatus = sanitize_key(wp_unslash($_POST['status'] ?? ''));
1758
+
1759
+ if (! wp_verify_nonce($nonceValue, 'update_order_' . $orderId)) {
1760
+ wp_die(esc_html__('Security check failed.', 'acme-shop'), 403);
1761
+ }
1762
+
1763
+ $allowed = [OrderStatus::PROCESSING, OrderStatus::COMPLETE, OrderStatus::CANCELLED];
1764
+ if (! in_array($newStatus, $allowed, true)) {
1765
+ wp_die(esc_html__('Invalid status.', 'acme-shop'), 400);
1766
+ }
1767
+
1768
+ wp_update_post(['ID' => $orderId, 'post_status' => $newStatus]);
1769
+
1770
+ wp_safe_redirect(admin_url('admin.php?page=ec-orders&updated=1'));
1771
+ exit;
1772
+ }
1773
+ }
1774
+ ```
1775
+
1776
+ ### `src/WordPress/Init/TableInstaller.php`
1777
+
1778
+ ```php
1779
+ declare(strict_types=1);
1780
+
1781
+ namespace Acme\Ecommerce\WordPress\Init;
1782
+
1783
+ final class TableInstaller
1784
+ {
1785
+ private const DB_VERSION_OPTION = 'db_version';
1786
+ private const DB_VERSION = '1.0.0';
1787
+
1788
+ public static function register(): void
1789
+ {
1790
+ add_action('init', [self::class, 'maybeInstall']);
1791
+ }
1792
+
1793
+ public static function maybeInstall(): void
1794
+ {
1795
+ if ((string) get_option(self::DB_VERSION_OPTION, '') === self::DB_VERSION) {
1796
+ return;
1797
+ }
1798
+
1799
+ self::install();
1800
+ }
1801
+
1802
+ private static function install(): void
1803
+ {
1804
+ global $wpdb;
1805
+
1806
+ $charset = $wpdb->get_charset_collate();
1807
+
1808
+ $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}ec_stock (
1809
+ id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
1810
+ product_id bigint(20) unsigned NOT NULL DEFAULT 0,
1811
+ quantity int(11) NOT NULL DEFAULT 0,
1812
+ updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
1813
+ PRIMARY KEY (id),
1814
+ UNIQUE KEY product_id (product_id)
1815
+ ) $charset;";
1816
+
1817
+ require_once ABSPATH . 'wp-admin/includes/upgrade.php';
1818
+ dbDelta($sql);
1819
+
1820
+ update_option(self::DB_VERSION_OPTION, self::DB_VERSION, false);
1821
+ }
1822
+ }
1823
+ ```
1824
+
1825
+ ### `src/Product/ProductManager.php`
1826
+
1827
+ ```php
1828
+ declare(strict_types=1);
1829
+
1830
+ namespace Acme\Ecommerce\Product;
1831
+
1832
+ final class ProductManager
1833
+ {
1834
+ public function __construct(
1835
+ private readonly \wpdb $wpdb,
1836
+ ) {}
1837
+
1838
+ public function getProduct(int $productId): ?array
1839
+ {
1840
+ $row = $this->wpdb->get_row(
1841
+ $this->wpdb->prepare(
1842
+ "SELECT * FROM {$this->wpdb->posts} WHERE ID = %d AND post_type = %s",
1843
+ $productId,
1844
+ 'product'
1845
+ ),
1846
+ ARRAY_A
1847
+ );
1848
+ return $row ?: null;
1849
+ }
1850
+
1851
+ public function getProducts(array $args = []): array
1852
+ {
1853
+ $query = new \WP_Query(array_merge([
1854
+ 'post_type' => 'product',
1855
+ 'posts_per_page' => -1,
1856
+ 'orderby' => 'title',
1857
+ 'order' => 'ASC',
1858
+ ], $args));
1859
+ return $query->posts;
1860
+ }
1861
+ }
1862
+ ```
1863
+
1864
+ ### `src/WordPress/Init/ShipmentCptRegistrar.php`
1865
+
1866
+ ```php
1867
+ declare(strict_types=1);
1868
+
1869
+ namespace Acme\Ecommerce\WordPress\Init;
1870
+
1871
+ final class ShipmentCptRegistrar
1872
+ {
1873
+ public const POST_TYPE = 'shipment';
1874
+
1875
+ public static function register(): void
1876
+ {
1877
+ add_action('init', [self::class, 'registerTypes']);
1878
+ }
1879
+
1880
+ public static function registerTypes(): void
1881
+ {
1882
+ register_post_type(self::POST_TYPE, [
1883
+ 'label' => __('Shipments', 'acme-shop'),
1884
+ 'public' => false,
1885
+ 'show_ui' => true,
1886
+ 'show_in_menu' => false,
1887
+ 'show_in_rest' => false,
1888
+ 'publicly_queryable' => false,
1889
+ 'supports' => ['title'],
1890
+ ]);
1891
+ }
1892
+ }
1893
+ ```
1894
+
1895
+ ### `src/Shipping/ShippingManager.php`
1896
+
1897
+ ```php
1898
+ declare(strict_types=1);
1899
+
1900
+ namespace Acme\Shipping;
1901
+
1902
+ final class ShippingManager
1903
+ {
1904
+ public function __construct(
1905
+ private readonly \wpdb $wpdb,
1906
+ ) {}
1907
+
1908
+ public static function queueForOrder(int $orderId, array $items): void
1909
+ {
1910
+ // Implementation would create shipment records, queue fulfillment, etc.
1911
+ }
1912
+
1913
+ public function createShipment(int $orderId, array $items): int
1914
+ {
1915
+ $postId = wp_insert_post([
1916
+ 'post_type' => 'shipment',
1917
+ 'post_title' => 'Shipment for Order #' . $orderId,
1918
+ 'post_status' => 'pending',
1919
+ ]);
1920
+
1921
+ if (is_wp_error($postId) || $postId === 0) {
1922
+ return 0;
1923
+ }
1924
+
1925
+ update_post_meta($postId, '_order_id', $orderId);
1926
+ update_post_meta($postId, '_items', $items);
1927
+
1928
+ do_action('shipment_created', $postId, $orderId, $items);
1929
+
1930
+ return $postId;
1931
+ }
1932
+ }
1933
+ ```
1934
+
1935
+ ### `src/WordPress/Init/AudioCptRegistrar.php`
1936
+
1937
+ ```php
1938
+ declare(strict_types=1);
1939
+
1940
+ namespace Vendor\Audios\WordPress\Init;
1941
+
1942
+ final class AudioCptRegistrar
1943
+ {
1944
+ public const POST_TYPE_AUDIOBOOK = 'audiobook';
1945
+ public const POST_TYPE_AUDIOFILE = 'audiofile';
1946
+
1947
+ public static function register(): void
1948
+ {
1949
+ add_action('init', [self::class, 'registerTypes']);
1950
+ }
1951
+
1952
+ public static function registerTypes(): void
1953
+ {
1954
+ register_post_type(self::POST_TYPE_AUDIOBOOK, [
1955
+ 'label' => __('Audiobooks', 'audios'),
1956
+ 'public' => true,
1957
+ 'show_ui' => true,
1958
+ 'show_in_rest' => true,
1959
+ 'publicly_queryable' => true,
1960
+ 'has_archive' => true,
1961
+ 'rewrite' => ['slug' => 'audiobooks'],
1962
+ 'supports' => ['title', 'editor', 'thumbnail', 'excerpt'],
1963
+ ]);
1964
+
1965
+ register_post_type(self::POST_TYPE_AUDIOFILE, [
1966
+ 'label' => __('Audio Files', 'audios'),
1967
+ 'public' => true,
1968
+ 'show_ui' => true,
1969
+ 'show_in_rest' => true,
1970
+ 'publicly_queryable' => true,
1971
+ 'has_archive' => true,
1972
+ 'rewrite' => ['slug' => 'audiofiles'],
1973
+ 'supports' => ['title', 'editor'],
1974
+ ]);
1975
+ }
1976
+ }
1977
+ ```
1978
+
1979
+ ### Hook surface summary
1980
+
1981
+ ```
1982
+ register_post_types fired after CPT/taxonomy registration
1983
+ order_created ($orderId, $customerId, $lineItems)
1984
+ order_status_changed ($orderId, $previousStatus, $newStatus)
1985
+ order_completed ($orderId)
1986
+ ```
1987
+
1988
+ An addon wires itself purely through its own registrar classes:
1989
+
1990
+ ```php
1991
+ // shipping-addon/src/WordPress/Init/ShipmentRegistrar.php
1992
+ namespace Acme\Shipping\WordPress\Init;
1993
+
1994
+ final class ShipmentRegistrar
1995
+ {
1996
+ public static function register(): void
1997
+ {
1998
+ add_action('order_created', [self::class, 'onOrderCreated'], 10, 3);
1999
+ add_action('register_post_types', [ShipmentCptRegistrar::class, 'registerTypes']);
2000
+ }
2001
+
2002
+ public static function onOrderCreated(int $orderId, int $customerId, array $items): void
2003
+ {
2004
+ \Acme\Shipping\ShippingManager::queueForOrder($orderId, $items);
2005
+ }
2006
+ }
2007
+ ```
2008
+
2009
+ ```php
2010
+ // shipping-addon/src/Plugin.php
2011
+ namespace Acme\Shipping;
2012
+
2013
+ final class Plugin
2014
+ {
2015
+ public static function init(): void
2016
+ {
2017
+ WordPress\Init\ShipmentRegistrar::register();
2018
+ }
2019
+ }
2020
+ ```
2021
+
2022
+ Base knows nothing about shipping. Shipping knows the base. Zero upward coupling.
2023
+
2024
+ ---
2025
+
2026
+ ## 22. Prohibited Patterns
2027
+
2028
+ | Anti-pattern | Why |
2029
+ |---|---|
2030
+ | `"files": ["bootstrap.php"]` | Breaks pure PSR-4, defeats autoload |
2031
+ | `if (!function_exists(...))` | Hides errors, prevents autoload |
2032
+ | Global `$sc_` variables | Destroys testability |
2033
+ | Helper function files | Use class methods |
2034
+ | `wp_json_encode()` → `meta_query LIKE` | Use taxonomies |
2035
+ | Mixed prefix naming | Standardize on clean keys |
2036
+ | Inline JS with PHP vars | Use `wp_localize_script` |
2037
+ | Hardcoded importer list | Registration pattern |
2038
+ | `__FILE__` in activation hooks | Brittle in PSR-4 packages; use `init` + version check (see §11 `TableInstaller::maybeInstall()`) |
2039
+ | Non-`final` classes | Prevents compiler optimization |
2040
+ | Missing `declare(strict_types=1)` | Weak typing, hidden bugs |
2041
+ | Docblocks on simple typed methods | Visual noise, redundant |
2042
+ | `public` properties | Breaks encapsulation |
2043
+ | `ai did this` comments | Remove them |