Core Developer Guide
Overview
The Core layer (src/Core/) is the shared toolkit every module builds on: database access, caching, settings, permissions, document numbers, audit logging, REST helpers and schema migrations. Modules never write raw SQL in controllers; each request flows down the same four layers.
- Module (
WPWM_Products_Module) registers hooks and routes. - Controller (extends
WPWM_REST_Controller) checks permissions, reads the request, shapes the JSON. - Service (
WPWM_Product_Service) holds business rules: validation, transactions, stock changes, audit entries. - Repository (extends
WPWM_Repository) is the only place that talks to a table.
Naming rules
- Every class starts with
WPWM_and uses underscores:WPWM_Product_Service. No namespaces. - Every class must be listed in
src/autoload.php(lowercase class name → file path undersrc/). A missing line = “Class not found”. - Tables are
{prefix}wpwm_<name>, capabilities and roleswpwm_*, REST routes/wp-json/wpwm/v1/*, text domainwarehouse-manager. - Plugin data lives only in the plugin's own tables. The one exception is users, roles and capabilities, which stay in WordPress.
| File | Class | One-line purpose |
|---|---|---|
| Core/Database.php | WPWM_Database | Table names, transactions, UTC time, error checks |
| Core/DatabaseException.php | WPWM_Database_Exception | Thrown when a query fails |
| Core/QueryBuilder.php | WPWM_Query_Builder | Safe, prepared WHERE clauses |
| Core/Repository.php | WPWM_Repository | Base class for table access and paginated lists |
| Core/Cache.php | WPWM_Cache | Object-cache helpers with group invalidation |
| Core/Settings.php | WPWM_Settings | Plugin settings in the {prefix}wpwm_settings table |
| Core/Sequence.php | WPWM_Sequence | Atomic document numbers (PO-000001) |
| Core/Capabilities.php | WPWM_Capabilities | Roles and capabilities |
| Core/AuditLog.php | WPWM_Audit_Log | Who changed what |
| Core/Rest/Controller.php | WPWM_REST_Controller | Base class for REST endpoints |
| Core/Migrations/Migration.php | WPWM_Migration | Base class for schema migrations |
| Core/Migrator.php | WPWM_Migrator | Runs pending migrations |
| Core/Installer.php | WPWM_Installer | Activation and upgrade entry point |
Plugin directories
Where things live in the plugin folder (wp-content/plugins/wms/), and where to put new code.
wms/
├── wms.php Plugin header and bootstrap (loads src/autoload.php, starts WPWM_Plugin)
├── uninstall.php Clean-up when the plugin is deleted
├── src/ PHP classes (all named WPWM_*, listed in src/autoload.php)
│ ├── autoload.php Class name → file map
│ ├── Plugin.php Runs pending upgrades, registers the modules and the app router
│ ├── Core/ Shared toolkit: database, cache, settings, roles, REST base classes, migrations
│ ├── Frontend/ The app at {home}/wms/: page registry, router, CSS/JS loading
│ └── Modules/ One folder per feature (Products, PurchaseOrders, Users, …)
├── templates/ HTML the app shows (PHP templates, no business rules)
│ ├── layout.php The frame around every page: sidebar, top bar, theme
│ ├── login.php The sign-in page (/wms/login/), a page of its own
│ ├── pages/ One file per screen (a URL)
│ ├── partials/ Building blocks shared by several pages
│ └── config/ Settings arrays for list and form pages (no HTML)
├── assets/
│ ├── css/app.css All app styles, including the colour themes
│ └── js/ app.js (shared helpers) and pages/*.js (one script per screen type)
├── languages/ Translation files (text domain warehouse-manager)
└── docs/ This guide
src/ — the PHP code
| Folder | What goes here | Examples |
|---|---|---|
| Core/ | Code every module uses. No feature-specific rules. Documented in the rest of this guide. | Database.php, Repository.php, Capabilities.php, DocumentSnapshot.php |
| Core/Rest/ | REST base classes. CrudController.php gives a module list / show / create / update / delete / bulk routes for free. | Controller.php, CrudController.php |
| Core/Migrations/ | Numbered schema changes. Never edit one that has shipped; add the next number. | Migration0001InitialSchema.php |
| Frontend/ | The app shell: which pages exist and who may open them (Pages.php), URL handling and wp-admin redirects (Router.php), loading CSS/JS and the REST nonce (Assets.php). | Pages.php, Router.php, Assets.php |
| Modules/<Name>/ | One feature, in four layers: Module (registers routes) → Controller (REST, permissions, JSON shape) → Service (business rules) → Repository (the table). | SalesOrders/SalesOrdersModule.php, …Controller.php, …Service.php, …Repository.php |
templates/ — what the app shows
The three folders split a screen into which screen it is (pages), reusable pieces (partials) and what to put in them (config).
| Folder | What it is | Examples |
|---|---|---|
| layout.php | The frame around every app page: sidebar menu (from WPWM_Pages), top bar, account menu, the theme colour (WPWM_Options::html_attributes()). | — |
| login.php | The sign-in page at /wms/login/: a full page without the menu, with the theme colour and logo. Visitors who aren't signed in are sent here, and come back to the page they asked for. | — |
| pages/ | The screens. The router picks one per URL from the page registry: 'template' for the list or main screen, 'form' for its add / edit screen. | dashboard.php, settings.php, sales-orders.php (list), sales-order-form.php (add / edit), error.php |
| partials/ | Building blocks shared by several pages. Never a screen on their own. | lookup-page.php (search, filters, table, paging, bulk delete), form-page.php, form-fields.php, pagination.php |
| config/ | A PHP file that returns an array: columns, filters, form fields, labels and capabilities for one list. No HTML. | customers.php, sales-orders.php, users.php |
Two kinds of form page. Simple records (Categories, Units, Customers, Suppliers, System User) share pages/lookup-form.php, which draws the fields listed in their config file, so they need no form file of their own. Documents with their own behaviour have a custom form: product-form.php (variations, stock), purchase-order-form.php (lines, receiving), sales-order-form.php (lines, deliveries) and invoice-form.php (billing, payments).
assets/ — styles and scripts
| File | What it does |
|---|---|
| css/app.css | Every app style. Colours are CSS variables at the top: the default theme colour's tuned shades, a :root[data-wpwm-color] block that works shades out from a chosen theme colour, and dark mode. |
| js/app.js | Loaded on every app page: WPWM.api() (REST with the nonce), WPWM.el(), WPWM.money(), WPWM.sprintf(), toasts, searchable selects, menus, password show / hide, theme preview. |
| js/pages/*.js | One script per kind of screen, e.g. lookup.js (every list page), form.js (every form), order-lines.js (PO / SO lines), dashboard.js. A page names its script in the registry ('script'); otherwise pages/<template>.js is loaded if it exists. |
How one screen comes together
Example: {home}/wms/sales-orders/
Frontend/Router.phpmatches the URL, checks the user may open the page (WPWM_Pages::can_view()) and wraps it intemplates/layout.php.- Inside the layout it loads
templates/pages/sales-orders.php. - That page loads
templates/partials/lookup-page.phpwithtemplates/config/sales-orders.php. - The partial builds the table from the config's columns and filters, with the first page of rows from the module's service (
WPWM_Sales_Order_Service::list()). assets/js/pages/lookup.jstakes over in the browser: search, sorting, paging and delete call the REST routes fromModules/SalesOrders/SalesOrderController.php.
Where to put new code
| You want to… | Add or change |
|---|---|
| Add a feature with its own data | A folder in src/Modules/ (Module, Controller, Service, Repository), a migration for its table, lines in src/autoload.php, the module in Plugin.php. See the checklist. |
| Add a simple list + add / edit screen | A templates/config/<name>.php, a page entry in Frontend/Pages.php ('config', 'form' => 'lookup-form') and a short templates/pages/<name>.php. |
| Add a screen with custom behaviour | A template in templates/pages/ and, if needed, a script in assets/js/pages/. |
| Add a menu entry for a PRO-only feature | A page entry with 'template' => null: it shows an “Add on” badge and links to the PRO site. |
| Change the database | A new numbered file in src/Core/Migrations/, listed in Migrator.php and autoload.php. |
| Add a setting | A field on a tab in Modules/Settings/SettingsRegistry.php; read it with WPWM_Options::get(). |
| Change the colours | No code: Settings → General → Theme colour (one colour; hover, highlight and readable text colours are worked out from it, see WPWM_Options::html_attributes()). Other colours: the variables at the top of assets/css/app.css. |
WPWM_Database
src/Core/Database.php
Static helpers around $wpdb. Use it whenever you need a table name, a transaction, the current time for a timestamp column, or to check a raw query.
| Method | Returns | Use it to |
|---|---|---|
table( string $name ) | string | Get the full table name: table( 'products' ) → wp_wpwm_products |
transaction( callable $callback ) | whatever the callback returns | Run several writes all-or-nothing. The callback receives $wpdb |
now() | string | Current UTC time as Y-m-d H:i:s for created_at / updated_at |
assert_ok( mixed $result ) | void | Throw WPWM_Database_Exception if a $wpdb call returned false |
Transactions
$po_id = WPWM_Database::transaction( function ( wpdb $wpdb ) use ( $data, $items ) {
$data['po_number'] = WPWM_Sequence::next( WPWM_Sequence::PURCHASE_ORDER );
$po_id = $this->orders->insert( $data );
foreach ( $items as $item ) {
$this->items->insert( $item + array( 'po_id' => $po_id ) );
}
return $po_id; // returned to the caller
} );
- Any exception inside the callback rolls back every write, then re-throws.
- Nested calls join the outer transaction: a service can call another service that also uses
transaction()safely. Only the outermost call commits. - Keep transactions short: no HTTP calls, emails or PDF generation inside them.
Raw queries
global $wpdb;
$table = WPWM_Database::table( 'stock' );
$result = $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET qty_reserved = 0 WHERE warehouse_id = %d", $warehouse_id ) );
WPWM_Database::assert_ok( $result ); // throws on SQL error instead of failing silently
All stored datetimes are UTC. Convert to the site timezone only when displaying.
WPWM_Database_Exception
src/Core/DatabaseException.php
Extends PHP's RuntimeException. It means a database operation failed; its message is MySQL's error text.
Thrown by:
WPWM_Database::assert_ok(), and therefore byWPWM_Repository::insert(),update()anddelete()WPWM_Sequence::next()when the document type doesn't existWPWM_Settings::set()andcreate_table()WPWM_Migration::create_table()when a table could not be created
How to handle it
- In controllers, wrap handlers in
guard()(see WPWM_REST_Controller). It logs the error and returns a clean 500 without leaking SQL. - Catch it in a service only when you can turn it into a user-facing message. The common case is a unique-index race:
try {
$id = $this->products->insert( $data );
} catch ( WPWM_Database_Exception $e ) {
if ( str_contains( $e->getMessage(), 'Duplicate entry' ) ) {
return new WP_Error( 'wms_invalid_product', __( 'Please fix the highlighted fields.', 'wms' ),
array( 'status' => 400, 'errors' => array( 'sku' => __( 'This SKU is already used.', 'wms' ) ) ) );
}
throw $e; // anything else is a real failure
}
Never swallow it silently: an uncaught exception inside WPWM_Database::transaction() is what triggers the rollback.
WPWM_Query_Builder
src/Core/QueryBuilder.php
Builds a prepared WHERE clause from conditions. Repositories use it inside paginate(); use it directly for custom report queries. Column names must come from your code (a whitelist), never straight from the request.
| Method | Use it to |
|---|---|
where( $column, $op, $value = null ) | Add one condition (AND). Chainable |
search( array $columns, string $term ) | Add an OR-search across columns. Empty term = no condition |
to_sql() | Get the prepared WHERE … string, or '' when there are no conditions |
column( string $column ) (static) | Validate an identifier (name, p.name); throws InvalidArgumentException otherwise |
Operators for where()
$op | SQL | Example |
|---|---|---|
= != > >= < <= | col = %s (ints → %d, floats → %f) | where( 'status', '=', 'active' ) |
in | col IN (…) from an array or comma string; empty → 1 = 0 | where( 'category_id', 'in', '3,7,9' ) |
prefix | col LIKE 'term%' — can use an index | where( 'sku', 'prefix', 'ABC' ) |
contains | col LIKE '%term%' — scans rows | where( 'name', 'contains', 'cola' ) |
null / not_null | col IS NULL / IS NOT NULL | where( 'deleted_at', 'null' ) |
Example: a custom query
$q = ( new WPWM_Query_Builder() )
->where( 'status', 'in', array( 'confirmed', 'picking' ) )
->where( 'order_date', '>=', '2026-11-01' )
->search( array( 'so_number' => 'prefix' ), $term );
$where = $q->to_sql(); // already prepared
$table = WPWM_Database::table( 'sales_orders' );
$rows = $wpdb->get_results( "SELECT id, so_number, total FROM {$table} {$where} ORDER BY order_date DESC LIMIT 50" );
Rules
to_sql()is already prepared. Never pass it through$wpdb->prepare()again; appendLIMIT/OFFSETas cast integers.- Use
prefixfor codes, SKUs and document numbers. Usecontainsfor names; switch to a FULLTEXTMATCHonce a table passes about 100,000 rows.
WPWM_Repository
src/Core/Repository.php
Abstract base class; one subclass per table. It is the only layer that writes SQL for that table, and it gives you caching, pagination, soft deletes and timestamps for free.
1. Declare the table
final class WPWM_Supplier_Repository extends WPWM_Repository {
protected string $table = 'suppliers'; // without prefix
protected array $fields = array( // writable columns => format
'code' => '%s', 'name' => '%s', 'email' => '%s',
'tax_id' => '%s', 'status' => '%s', 'created_by' => '%d',
);
protected array $list_columns = array( 'id', 'code', 'name', 'email', 'status', 'updated_at' );
protected array $sortable = array( 'id', 'code', 'name', 'updated_at' );
protected string $default_orderby = 'name';
protected string $default_order = 'ASC';
protected array $filters = array( 'status' => array( 'status', '=' ) ); // request arg => [column, op]
protected array $searchable = array( 'code' => 'prefix', 'name' => 'contains' );
protected bool $soft_deletes = true;
}
| Property | Default | Meaning |
|---|---|---|
$table | — (required) | Table name without wp_wpwm_ |
$fields | [] | Only these keys are written; others are dropped silently. Use '%s' for DECIMAL columns to keep exact precision |
$list_columns | ['*'] | Columns paginate() selects. Keep it to what list screens show |
$sortable | ['id'] | Allowed orderby values. Each should be covered by an index |
$default_orderby / $default_order | id / DESC | Used when the request gives none or an invalid one |
$filters | [] | Request args mapped to [column, operator] (operators: see WPWM_Query_Builder) |
$searchable | [] | Columns for search, each 'prefix' or 'contains' |
$soft_deletes | false | delete() sets deleted_at; lists and find() skip deleted rows |
$timestamps | true | Fills created_at / updated_at automatically |
2. Use it
| Method | Returns | Notes |
|---|---|---|
find( int $id, bool $with_trashed = false ) | ?object | Cached per row |
find_many( array $ids ) | array<int, object> keyed by id | One query for many rows; use it to avoid N+1 loops |
paginate( array $args ) | ['items', 'total', 'page', 'per_page', 'total_pages'] | Reads page, per_page (max 100), search, orderby, order + your filters |
insert( array $data ) | int new id | Throws WPWM_Database_Exception on failure |
update( int $id, array $data ) | void | Partial update; only keys in $fields |
delete( int $id ) | void | Soft or hard, depending on $soft_deletes |
forget( int $id ) | void | Clear the row cache and invalidate lists. Call after any raw SQL write to this table |
table() / cache_group() | string | Full table name / cache group wpwm_<table> |
$repo = new WPWM_Supplier_Repository();
$page = $repo->paginate( array( 'search' => 'acme', 'status' => 'active', 'page' => 2, 'per_page' => 25 ) );
$id = $repo->insert( array( 'code' => 'SUP-001', 'name' => 'Acme Trading' ) );
$repo->update( $id, array( 'email' => 'orders@acme.test' ) );
$byId = $repo->find_many( array_column( $orders, 'supplier_id' ) ); // then $byId[ $order->supplier_id ]
3. Add custom rules by overriding build_query()
Example: drivers only see sales orders assigned to them.
protected function build_query( array $args ): WPWM_Query_Builder {
$query = parent::build_query( $args ); // keeps soft deletes, filters and search
if ( ! current_user_can( WPWM_Capabilities::VIEW_ALL_SO ) ) {
$query->where( 'driver_id', '=', get_current_user_id() );
}
return $query;
}
Put custom queries (totals, joins, reports) as extra public methods on the repository, like stock_totals() in WPWM_Product_Repository. Services and controllers never write SQL.
WPWM_Cache
src/Core/Cache.php
Helpers on top of the WordPress object cache. Each cache group carries a last_changed stamp; putting that stamp in your cache key means one bump() invalidates every cached list and count in the group at once.
| Method | Use it to |
|---|---|
last_changed( string $group ) | Get the group's current stamp, for building cache keys |
bump( string $group ) | Invalidate everything keyed with the old stamp. Call after a write |
remember( $key, $group, callable $callback, int $ttl = 0 ) | Return the cached value, or run the callback once and cache its result |
Example: cache a dashboard number
$group = 'wpwm_sales_orders';
$key = 'open-count:' . WPWM_Cache::last_changed( $group );
$open = WPWM_Cache::remember( $key, $group, function () use ( $wpdb ) {
$table = WPWM_Database::table( 'sales_orders' );
return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE status IN ('confirmed','picking','packed')" );
} );
Any insert(), update() or delete() through WPWM_Repository already bumps the table's group (wpwm_<table>), so the number above refreshes after the next order change.
Good to know
- Without a persistent object cache (Redis, Memcached) the cache lasts one request. That is always safe, just less useful.
- With one installed, repeated list, count and settings queries are skipped across requests. It is the single biggest speed-up for busy sites.
remember()cachesnullandfalseresults too, so an empty result is not re-queried.
WPWM_Settings
src/Core/Settings.php
Plugin settings stored one row per key in wp_wpwm_settings, never in wp_options. Values are saved as JSON, so strings, numbers, booleans and arrays come back with their type. All rows are read once per request and kept in memory.
| Method | Use it to |
|---|---|
get( string $key, mixed $default = null ) | Read one setting |
all() | Read every setting as an array (e.g. to fill a settings form) |
set( string $key, mixed $value ) | Save one setting (insert or update). Throws WPWM_Database_Exception on failure |
set_many( array $values ) | Save several settings in one transaction |
add_missing( array $defaults ) | Insert keys that don't exist yet; never overwrites saved values |
delete( string $key ) | Remove a setting |
flush() | Drop the in-memory copy so the next get() re-reads the table |
$currency = WPWM_Settings::get( 'currency', 'USD' );
WPWM_Settings::set_many( array(
'company_name' => 'Acme Warehouse',
'tax_rate' => '12',
'allow_negative_stock' => false,
) );
Default settings
From WPWM_Installer::default_settings(), added after every upgrade.
| Key | Default | Meaning |
|---|---|---|
company_name | the site title | Shown on invoices and POs |
company_address | '' | Shown on printed documents |
currency | USD | Currency code |
tax_rate | '0' | Default tax rate, as a decimal string |
allow_negative_stock | false | Whether stock may go below zero |
remove_data_on_uninstall | false | Drop all plugin tables when the plugin is deleted |
db_version and migration_error (constants WPWM_Settings::DB_VERSION, MIGRATION_ERROR) belong to the migrator. Don't edit them from a settings screen.To add a new setting: add it with its default to WPWM_Installer::default_settings(). Existing sites get the row on the next activation or schema upgrade, without touching their other values. Until then, always pass the same default to get().
WPWM_Sequence
src/Core/Sequence.php
Hands out document numbers such as PO-000001. The increment and read happen in one SQL statement, so two users saving at the same moment never get the same number.
WPWM_Sequence::next( string $doc_type ): string returns the next formatted number.
| Constant | doc_type | Seeded format |
|---|---|---|
PURCHASE_ORDER | purchase_order | PO-000001 |
RECEIPT | receipt | RCV-000001 |
SALES_ORDER | sales_order | SO-000001 |
INVOICE | invoice | INV-000001 |
PAYMENT | payment | PAY-000001 |
WPWM_Database::transaction( function () use ( $data ) {
$data['so_number'] = WPWM_Sequence::next( WPWM_Sequence::SALES_ORDER );
return $this->orders->insert( $data );
} );
- Call it inside the same transaction as the insert. If the save fails and rolls back, the number is rolled back too, so there are no gaps.
- An unknown type throws
WPWM_Database_Exception. - Prefix, padding and the last number used live in the
wp_wpwm_sequencestable (prefix,padding,last_no). Change them there, e.g. from a Settings screen. - To add a document type: add a constant here, then insert its row in a new migration (
INSERT IGNORE INTO … (doc_type, prefix, last_no, padding)).
WPWM_Capabilities
src/Core/Capabilities.php
Defines the five WMS roles and 20 capabilities. Always check a capability, never a role name: current_user_can( WPWM_Capabilities::APPROVE_PO ). The WordPress administrator role is the WMS Admin and receives every capability.
| Capability (constant) | Admin | Manager | Accounting | Purchaser | Clerk | Driver |
|---|---|---|---|---|---|---|
VIEW_PRODUCTS | ✓ | ✓ | ✓ | ✓ | ✓ | |
MANAGE_PRODUCTS | ✓ | ✓ | ||||
VIEW_SUPPLIERS | ✓ | ✓ | ✓ | ✓ | ||
MANAGE_SUPPLIERS | ✓ | ✓ | ✓ | |||
VIEW_CUSTOMERS | ✓ | ✓ | ✓ | ✓ | ||
MANAGE_CUSTOMERS | ✓ | ✓ | ✓ | |||
VIEW_PO | ✓ | ✓ | ✓ | ✓ | ✓ | |
CREATE_PO | ✓ | ✓ | ✓ | |||
APPROVE_PO | ✓ | ✓ | ||||
RECEIVE_STOCK | ✓ | ✓ | ✓ | |||
ADJUST_STOCK | ✓ | ✓ | ||||
VIEW_SO | ✓ | ✓ | ✓ | ✓ | ✓ | |
VIEW_ALL_SO | ✓ | ✓ | ✓ | ✓ | ||
MANAGE_SO | ✓ | ✓ | ✓ | |||
DELIVER | ✓ | ✓ | ✓ | |||
MANAGE_INVOICES | ✓ | ✓ | ✓ | |||
MANAGE_PAYMENTS | ✓ | ✓ | ✓ | |||
VIEW_REPORTS | ✓ | ✓ | ✓ | |||
MANAGE_USERS | ✓ | |||||
MANAGE_SETTINGS | ✓ |
Role keys: administrator, wpwm_manager, wpwm_accounting, wpwm_sales. A role with VIEW_SO but not VIEW_ALL_SO is meant to see only the sales orders where driver_id is their own user id; the dashboard applies that rule, and the sales-order repository should too before such a role is added.
| Method | Use it to |
|---|---|
roles() | Get the role map: key → label + capabilities |
sync() | Create the roles and make each role's capabilities match the map exactly. Runs on activation and after every schema upgrade |
remove() | Delete the WMS roles and the administrator's WMS capabilities (used by uninstall) |
assignable_roles() | Roles the current user may give in a Users screen. administrator is offered only to users WordPress lets promote users |
In a REST route
'permission_callback' => $this->can( WPWM_Capabilities::RECEIVE_STOCK ),
To add or change a capability
- Add the constant and include it in
ALL. - Add it to the roles that need it in
roles(). sync()only runs on activation or a schema upgrade: deactivate and reactivate the plugin locally, and ship a migration (even an empty one) so existing sites re-sync.
assignable_roles(). Otherwise a user with MANAGE_USERS could create an administrator.WPWM_Audit_Log
src/Core/AuditLog.php
Records who changed what in wp_wpwm_audit_log. Each row stores the user id, entity, entity id, action, the changes as JSON, the IP address and a UTC timestamp.
| Method | Use it to |
|---|---|
record( string $entity, int $entity_id, string $action, array $changes = [] ) | Write one entry. Never throws: a failed audit insert must not break a save |
diff( object $before, array $after ) | Get only the fields that changed, as field => ['from' => …, 'to' => …] |
$existing = $this->suppliers->find( $id );
$changes = WPWM_Audit_Log::diff( $existing, $data );
if ( $changes ) {
$this->suppliers->update( $id, $data );
WPWM_Audit_Log::record( 'supplier', $id, 'updated', $changes );
}
Conventions
entity: singular, lowercase —product,supplier,purchase_order,invoice.action: past tense —created,updated,deleted,approved,received,voided,paid.- Call it from services, after the write succeeds, inside the same transaction when there is one.
- Skip the entry when
diff()is empty, so saving an unchanged form leaves no noise. - Never put passwords or tokens in
$changes.
WPWM_REST_Controller
src/Core/Rest/Controller.php
Abstract base for every endpoint under /wp-json/wpwm/v1/. Subclasses implement register_routes() and use the helpers below. Front-end calls authenticate with the login cookie plus an X-WP-Nonce header created with wp_create_nonce( 'wp_rest' ).
| Member | Use it to |
|---|---|
NAMESPACE | The route namespace, wpwm/v1 |
register_routes() (abstract) | Call register_rest_route() for your module |
can( string $capability ) | Build a permission_callback that checks one capability |
collection_args( array $orderby, array $extra = [] ) | Standard list args: page, per_page (1–100, default 25), search, orderby (your list), order (asc/desc), plus your filters, all validated and sanitized |
paginated( array $result, callable $prepare ) | Turn a paginate() result into a response with X-WP-Total and X-WP-TotalPages headers |
guard( callable $handler ) | Run a handler; return WP_Error as is; turn any exception into a logged 500 wms_server_error |
not_found() | A 404 wms_not_found error |
final class WPWM_Supplier_Controller extends WPWM_REST_Controller {
public function __construct( private WPWM_Supplier_Service $service ) {}
public function register_routes(): void {
register_rest_route( self::NAMESPACE, '/suppliers', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'index' ),
'permission_callback' => $this->can( WPWM_Capabilities::VIEW_SUPPLIERS ),
'args' => $this->collection_args(
array( 'id', 'code', 'name', 'updated_at' ),
array( 'status' => array( 'type' => 'string', 'enum' => array( 'active', 'inactive' ) ) )
),
),
) );
}
public function index( WP_REST_Request $request ) {
return $this->guard( fn() => $this->paginated(
$this->service->list( $request->get_params() ),
array( $this, 'prepare' )
) );
}
public function prepare( object $row ): array {
return array( 'id' => (int) $row->id, 'code' => $row->code, 'name' => $row->name, 'status' => $row->status );
}
}
Response conventions
- Validation errors: status 400, code
wms_invalid_<entity>, withdata.errors=field => messageso forms can highlight fields. - Created: status 201 with the new record. Deleted:
{ "deleted": true }. - Decimals (money, quantities) are sent as strings so they never pick up float rounding.
- Every route needs a
permission_callback; never use__return_truefor WMS data.
WPWM_Migration and migration 0001
src/Core/Migrations/Migration.php · src/Core/Migrations/Migration0001InitialSchema.php
WPWM_Migration is the abstract base for one schema change. Each migration implements up(); the helper create_table( $name, $definition ) adds the wp_wpwm_ prefix, ENGINE=InnoDB and the site charset, runs WordPress's dbDelta(), then throws WPWM_Database_Exception if the table does not exist afterwards.
WPWM_Migration_0001_Initial_Schema creates 20 tables in groups — catalog, inventory, parties, purchasing, sales, billing, system — and seeds the document sequences, the MAIN warehouse and the PC, BOX, KG units. The 21st table, settings, is created by WPWM_Settings::create_table() before any migration runs.
dbDelta rules
Break one and the table is silently wrong.
- One column per line.
PRIMARY KEY (id)with two spaces before the bracket.- Write
KEY name (cols), notINDEX; give every index a name. - Lowercase types are fine (
bigint unsigned,decimal(15,4)); no foreign keys.
Column conventions
| Kind | Type |
|---|---|
| ids and user ids | bigint unsigned |
| quantities, unit costs | decimal(15,4) |
| money | decimal(15,2) |
| timestamps (UTC) | datetime |
| business dates | date |
| indexed text | varchar(191) or shorter |
Adding a migration
- Create
src/Core/Migrations/Migration0002AddBatchNumbers.php:
<?php
defined( 'ABSPATH' ) || exit;
final class WPWM_Migration_0002_Add_Batch_Numbers extends WPWM_Migration {
public function up(): void {
$this->create_table( 'batches', '
id bigint unsigned NOT NULL AUTO_INCREMENT,
product_id bigint unsigned NOT NULL,
batch_no varchar(64) NOT NULL,
expires_on date DEFAULT NULL,
created_at datetime NOT NULL,
updated_at datetime NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY product_batch (product_id,batch_no)' );
}
}
- Register it in
WPWM_Migrator::MIGRATIONS:2 => WPWM_Migration_0002_Add_Batch_Numbers::class. - Add it to
src/autoload.php. - Add any new table name to
WPWM_Installer::TABLESso uninstall drops it.
- Calling
create_table()again with an extra column adds it to an existing table. Dropping or renaming a column needs a plain$wpdb->query( 'ALTER TABLE …' ). - Never edit a migration that has been released: sites that already ran it will never run it again.
WPWM_Migrator
src/Core/Migrator.php
Runs pending migrations in version order and remembers the last one applied in the db_version setting. You rarely call it directly; WPWM_Installer::upgrade() does.
| Method | Returns | Meaning |
|---|---|---|
latest() | int | Highest version in MIGRATIONS |
current() | int | Version stored in wp_wpwm_settings (0 before install) |
needs_upgrade() | bool | current() < latest() |
run() | bool | Apply pending migrations; true when the schema is up to date |
last_error() | ?string | The last failure message, or null |
What run() does
- Returns
truestraight away if nothing is pending. - Takes a MySQL named lock (
GET_LOCK). If another request holds it, returnsfalseand lets that request finish. MySQL frees the lock by itself if a request crashes. - Creates the settings table if missing.
- Runs each pending migration's
up(), savingdb_versionafter each one, so a later failure never re-runs an earlier success. - On success, clears
migration_error. On failure, saves the message tomigration_errorand returnsfalse. - Releases the lock.
When it runs
- On plugin activation.
- On every page load where
needs_upgrade()is true, which is how plugin updates apply new migrations. - After a failure, only wp-admin page loads retry, so visitors never trigger table changes on every request. Administrators see the error as an admin notice.
db_version row from wp_wpwm_settings, then load any wp-admin page.WPWM_Installer
src/Core/Installer.php
The single entry point for installing and upgrading. wms.php registers activate() as the activation hook, and WPWM_Plugin::boot() calls upgrade() whenever the schema is behind.
| Member | Use it to |
|---|---|
activate() | Activation hook. Calls upgrade() |
upgrade() | Run migrations; if they succeed, add missing default settings and sync roles |
default_settings() | The default value of every plugin setting (see WPWM_Settings) |
TABLES | Every table the plugin owns, without prefix. uninstall.php drops these |
public static function upgrade(): void {
if ( WPWM_Migrator::run() ) {
WPWM_Settings::add_missing( self::default_settings() );
WPWM_Capabilities::sync();
}
}
Keep it in step
- New table → add its name to
TABLES. - New setting → add it with its default to
default_settings(). - New capability →
WPWM_Capabilities(it is synced here).
Uninstall: deleting the plugin from the Plugins screen runs uninstall.php. It drops every table in TABLES and removes the WMS roles, but only when the remove_data_on_uninstall setting is true. Otherwise all data is kept.
Checklist: adding a new module
Copy src/Modules/Products/ and rename. Example for Suppliers:
- Table exists in a migration (Suppliers is already in 0001; a new table needs a new migration +
WPWM_Installer::TABLES) WPWM_Supplier_RepositoryextendsWPWM_Repository:$table,$fields,$list_columns,$sortable,$filters,$searchable,$soft_deletesWPWM_Supplier_Service: validation returningWP_Errorwithdata.errors, transactions for multi-row writes,WPWM_Audit_Log::record()after each changeWPWM_Supplier_ControllerextendsWPWM_REST_Controller: routes,can()on every route,collection_args()on lists,guard()around every handler,prepare()for outputWPWM_Suppliers_ModuleimplementsWPWM_Moduleand registers the controller onrest_api_init- Module added to
$modulesinsrc/Plugin.php - Every new class added to
src/autoload.php - New capabilities added to
WPWM_Capabilitiesand roles re-synced - New settings added to
WPWM_Installer::default_settings() - Lists use
paginate()orfind_many(), never a query per row php -lpasses on every new file
Overriding templates
src/Frontend/Router.php · WPWM_Router::locate_template(), load_template(), config()
A theme or another plugin can change how the app looks without editing the plugin, so changes survive plugin updates. There are four ways in; prefer the lightest one that does the job.
| You want to… | Use | Copies a file? |
|---|---|---|
| Add something above or below a page or part (a notice, a banner, a help link) | Actions wpwm_before_template / wpwm_after_template | No |
| Change a list or form: add / remove a column, a filter, a form field, a text | Filter wpwm_page_config | No |
| Change a template's HTML, from a theme | Copy it to {theme}/wms/ | Yes |
| Change a template's HTML, from a plugin | Filter wpwm_locate_template | Yes |
Where a template comes from
Every template is loaded through WPWM_Router::load_template( $name, $view ), which looks for {name}.php in this order and uses the first one found:
- the child theme:
wp-content/themes/{child-theme}/wms/{name}.php - the parent theme:
wp-content/themes/{theme}/wms/{name}.php - the plugin:
wp-content/plugins/wms/templates/{name}.php
The result then passes through the wpwm_locate_template filter. Template names are paths under templates/ without .php, lowercase letters, digits, hyphens and slashes only (anything else, such as ../, is refused).
| Name | What it is |
|---|---|
layout | The frame around every page: sidebar, top bar, account menu |
login | The sign-in page ($view: title, errors, notice, username, redirect_to, action). Keep the field names log, pwd, rememberme, redirect_to and the _wpwm_login nonce. |
pages/dashboard, pages/settings, pages/error, pages/customers, … | One screen each (see Plugin directories) |
pages/product-form, pages/purchase-order-form, pages/sales-order-form, pages/invoice-form, pages/lookup-form | Add / edit screens |
partials/lookup-page, partials/form-page, partials/form-fields, partials/pagination | Shared building blocks: overriding one changes every page that uses it |
config/customers, config/sales-orders, config/users, … | List / form settings (arrays, no HTML), loaded with WPWM_Router::config() |
From a theme: copy and edit
- Create a
wmsfolder in your (child) theme. - Copy the template from the plugin, keeping its path under
templates/. Example:wp-content/plugins/wms/templates/pages/dashboard.php→wp-content/themes/my-child-theme/wms/pages/dashboard.php. - Edit the copy. The plugin now uses it instead of its own.
<?php
// wp-content/themes/my-child-theme/wms/pages/dashboard.php
defined( 'ABSPATH' ) || exit;
?>
<section class="wpwm-panel">
<h2><?php echo esc_html( sprintf( 'Hello, %s', $view['user']->display_name ) ); ?></h2>
</section>
Use a child theme, so a theme update doesn't remove your copy.
From a plugin: wpwm_locate_template
Arguments: the file found, the template name, and the plugin's own file. Return the file to use.
add_filter( 'wpwm_locate_template', function ( string $file, string $name, string $default ): string {
if ( 'partials/pagination' === $name ) {
return __DIR__ . '/templates/wms-pagination.php';
}
return $file;
}, 10, 3 );
To wrap the original instead of replacing it, include $default from your file.
Change a list or form: wpwm_page_config
List pages and the shared add / edit form (lookup-form) read their columns, filters, form fields and texts from templates/config/{name}.php through WPWM_Router::config(). Change the array with a filter instead of copying the file: you keep getting the plugin's updates to everything else.
add_filter( 'wpwm_page_config', function ( array $config, string $name, array $view ): array {
if ( 'customers' === $name ) {
// A column (the key must be a field the list's REST endpoint returns).
$config['columns'][] = array( 'key' => 'tax_id', 'label' => __( 'Tax ID', 'my-plugin' ) );
// A text.
$config['i18n']['add'] = __( 'New customer', 'my-plugin' );
}
return $config;
}, 10, 3 );
A config file can also be overridden like a template ({theme}/wms/config/customers.php); the filter still runs on the result.
Add content around a template: actions
wpwm_before_template and wpwm_after_template run around every template with ( string $name, array $view ).
add_action( 'wpwm_before_template', function ( string $name, array $view ): void {
if ( 'pages/dashboard' === $name ) {
echo '<p class="wpwm-alert is-warning">' . esc_html__( 'Stock count on Friday.', 'my-plugin' ) . '</p>';
}
}, 10, 2 );
Writing an override safely
- Start from the plugin's current file and change as little as possible.
- Keep the
data-*attributes and JSON blocks (e.g.data-chart,id="wpwm-finance-data",data-wpwm-form): the page scripts inassets/js/pages/find the page by them. - Escape everything you print (
esc_html(),esc_attr(),esc_url()), and keepdefined( 'ABSPATH' ) || exit;at the top. $viewis in scope:slug,page,title,template,user(WP_User),action, plusid/recordon edit forms. Partials get the array they were loaded with (e.g.$view['lookup']inpartials/lookup-page).- Permissions are already checked before a page template runs; don't remove checks inside templates (e.g. who sees Issue / Void on invoices).
- After a plugin update, compare your copies with the plugin's new files. A copied template doesn't get the plugin's fixes; filters and actions do.
All hooks, with arguments and examples: Hooks & filters reference.
Hooks & filters reference
Every action and filter the plugin offers, for themes and other plugins. All names start with wpwm_. Add them from a plugin, or from a theme's functions.php; the plugin reads them when its pages load, so any normal plugin / theme load is early enough.
| Hook | Type | Arguments | Use it to |
|---|---|---|---|
wpwm_before_template | Action | string $name, array $view | Print something before a template |
wpwm_after_template | Action | string $name, array $view | Print something after a template |
wpwm_locate_template | Filter | string $file, string $name, string $default | Use your own file for a template |
wpwm_page_config | Filter | array $config, string $name, array $view | Change a list / form: columns, filters, fields, texts |
wpwm_pages | Filter | array $pages | Add, remove or change app pages and menu entries |
wpwm_settings_tabs | Filter | array $tabs | Add settings tabs, sections and fields |
wpwm_currencies | Filter | array $currencies | Add or change currencies |
wpwm_app_base | Filter | string $base | Move the app from {home}/wms/ |
wpwm_no_access_redirect | Filter | string $url, WP_User $user | Where users without a warehouse role go |
wpwm_login_redirect | Filter | string $url, WP_User $user | Where users go after signing in on the app's sign-in page |
wpwm_before_template / wpwm_after_template
src/Frontend/Router.php · WPWM_Router::load_template()
Run just before and just after every template is included, for every page and partial. $name is the template name (pages/dashboard, partials/lookup-page, layout, …); $view is the data the template gets (see Overriding templates). Echo HTML; escape it.
add_action( 'wpwm_after_template', function ( string $name, array $view ): void {
if ( 'pages/sales-orders' === $name ) {
echo '<p class="wpwm-field-hint">' . esc_html__( 'Orders confirmed after 3 pm ship next day.', 'my-plugin' ) . '</p>';
}
}, 10, 2 );
Tip: wpwm_after_template for layout runs after the page has ended; use the page's own template name instead.
wpwm_locate_template
src/Frontend/Router.php · WPWM_Router::locate_template()
The file used for a template, after the theme lookup ({child-theme}/wms/, {theme}/wms/, then the plugin). Return a path to a readable .php file; a path that doesn't exist makes the template show nothing.
| Argument | Value |
|---|---|
$file | The file found (a theme override, or the plugin's own) |
$name | Template name, e.g. pages/dashboard, partials/form-fields, config/customers |
$default | The plugin's own file (include it from yours to wrap the original) |
add_filter( 'wpwm_locate_template', function ( string $file, string $name ): string {
return 'pages/dashboard' === $name ? __DIR__ . '/templates/wms-dashboard.php' : $file;
}, 10, 2 );
wpwm_page_config
src/Frontend/Router.php · WPWM_Router::config()
The settings of a list page and its shared add / edit form (templates/config/{name}.php): columns, filters, form_sections / fields, i18n texts, manage_cap, delete_cap. Names: products, categories, units, customers, suppliers, purchase-orders, sales-orders, invoices, users. The column and field keys are documented at the top of templates/partials/lookup-page.php and templates/partials/form-fields.php.
add_filter( 'wpwm_page_config', function ( array $config, string $name ): array {
if ( 'suppliers' === $name ) {
// Hide the Email column on Suppliers.
$config['columns'] = array_values( array_filter( $config['columns'], fn( $c ) => 'email' !== $c['key'] ) );
}
return $config;
}, 10, 2 );
A column shows a field of the list's REST response, and a form field is saved only if the module's service accepts it: adding a brand-new data field also needs server-side code.
wpwm_pages
src/Frontend/Pages.php · WPWM_Pages::all()
The page registry: slug => definition. It builds the sidebar, the URLs ({home}/wms/{slug}/) and who may open each page.
| Key | Meaning |
|---|---|
title | Page title (and menu label) |
menu_title | Optional shorter menu label |
cap | Capability needed to see / open it (e.g. WPWM_Capabilities::VIEW_SO), or null for every app user |
template | Template under pages/, without .php; null = an add-on menu entry (“Add on” badge, links to the PRO site) |
group | Sidebar group: main, inventory, billing, contacts, admin |
parent | Optional parent slug: shown under it in the menu (URL {parent}/{child}) |
script | The plugin's page script to load (assets/js/pages/{script}.js), e.g. lookup, form |
config, form, form_titles, manage_cap, repository | For list pages with add / edit forms (see Plugin directories) |
Example: a page from another plugin. Supply its template with wpwm_locate_template (or a theme file at wms/pages/delivery-board.php), and its script with wpwm_after_template: the app prints only its own scripts, so print yours with defer to run after app.js (then WPWM.api(), WPWM.toast(), … are available).
add_filter( 'wpwm_pages', function ( array $pages ): array {
$pages['delivery-board'] = array(
'title' => __( 'Delivery board', 'my-plugin' ),
'cap' => WPWM_Capabilities::VIEW_SO,
'template' => 'delivery-board',
'group' => 'inventory',
);
return $pages;
} );
add_filter( 'wpwm_locate_template', function ( string $file, string $name ): string {
return 'pages/delivery-board' === $name ? __DIR__ . '/templates/delivery-board.php' : $file;
}, 10, 2 );
add_action( 'wpwm_after_template', function ( string $name ): void {
if ( 'pages/delivery-board' === $name ) {
printf( '<script src="%s" defer></script>', esc_url( plugins_url( 'js/delivery-board.js', __FILE__ ) ) );
}
} );
Removing an entry (unset( $pages['reports'] )) removes it from the menu and makes its URL a 404.
wpwm_settings_tabs
src/Modules/Settings/SettingsRegistry.php · WPWM_Settings_Registry::tabs()
The tabs on Settings: key => array( 'label' => …, 'sections' => array( … ) ). Each section has title, description and fields (same keys as form fields, plus default). Values are validated (selects must match an option, number min / max, color hex) and saved in the wpwm_settings option; read them with WPWM_Options::get( 'key' ).
add_filter( 'wpwm_settings_tabs', function ( array $tabs ): array {
$tabs['shipping'] = array(
'label' => __( 'Shipping', 'my-plugin' ),
'sections' => array(
array(
'title' => __( 'Cut-off', 'my-plugin' ),
'fields' => array(
array( 'name' => 'myplugin_cutoff_hour', 'label' => __( 'Cut-off hour', 'my-plugin' ), 'type' => 'number', 'min' => 0, 'max' => 23, 'default' => '15', 'span' => 1 ),
),
),
),
);
return $tabs;
} );
$hour = (int) WPWM_Options::get( 'myplugin_cutoff_hour' );
Prefix your field names: all tabs share one option.
wpwm_currencies
src/Modules/Settings/SettingsRegistry.php · WPWM_Settings_Registry::currencies()
The currencies offered on Settings → General: ISO code => array( name, symbol ). The symbol is used by WPWM_Options::money() and WPWM.money().
add_filter( 'wpwm_currencies', function ( array $currencies ): array {
$currencies['KES'] = array( __( 'Kenyan Shilling', 'my-plugin' ), 'KSh' );
return $currencies;
} );
wpwm_app_base
src/Frontend/Router.php · WPWM_Router::base()
The app's path under the site: wms → {home}/wms/. Lowercase letters, digits, - and / are kept; anything else is removed, and an empty result falls back to wms. The rewrite rules are rebuilt automatically on the next page load after it changes.
add_filter( 'wpwm_app_base', fn() => 'warehouse' ); // {home}/warehouse/
Pick a path no WordPress page or post uses.
wpwm_no_access_redirect
src/Frontend/Router.php · WPWM_Router::dispatch()
A signed-in user without any warehouse role (e.g. a subscriber or a customer account) who opens the app is sent away instead of seeing it. Default: the site's home page. Must be a URL on this site (it goes through wp_safe_redirect()). Users with a warehouse role who open a page their role doesn't include still see “Access denied” inside the app.
add_filter( 'wpwm_no_access_redirect', fn( string $url, WP_User $user ) => home_url( '/my-account/' ), 10, 2 );
The same filter decides where such a user goes after signing in on /wms/login/.
wpwm_login_redirect
src/Frontend/Router.php · WPWM_Router::login_page()
Where a user goes after signing in on the app's sign-in page (/wms/login/) when no app page was asked for. Default: the user's start page (the Dashboard, or the first page their role can open). When the user was sent to sign in from an app page, they go back to that page and this filter isn't used. Sign-in runs through wp_signon(), so WordPress's own login hooks (authenticate, wp_login, wp_login_failed) and security plugins that use them still apply.
add_filter( 'wpwm_login_redirect', fn( string $url, WP_User $user ) => WPWM_Pages::url( 'sales-orders' ), 10, 2 );