Hooks: Actions & Filters
Every action and filter Shaped Recommend exposes, plus the public functions that make up its extension seam.
If you're writing a theme tweak, a compatibility shim or an add-on, this page is the contract. Everything listed here is deliberate public API. Anything not listed (class internals, option layouts, table columns) can change between releases without notice.
Two prefixes, one rule: sprcm_ for data-level hooks and functions, shaped_recommend_ for the plugin's lifecycle actions.
Never hook before the boot chain fires
The plugin boots as a chain of actions rather than a chain of is_plugin_active() checks:
plugins_loaded (priority 20)
└── WooCommerce present and ≥ 7.0
└── shaped_recommend_loaded (fired by Free)
└── Free version ≥ Pro's floor
└── shaped_recommend_pro_loaded (fired by Pro)Register your integration on shaped_recommend_loaded (or shaped_recommend_pro_loaded if it needs Pro), never directly on plugins_loaded. Hooking earlier means running before the dependency gates have decided anything, and before any feature code has registered. Reading sprcm_capabilities() too early triggers a _doing_it_wrong() notice for exactly that reason.
Lifecycle actions
shaped_recommend_loaded
Fires once WooCommerce is confirmed active and new enough, and Free is ready to load. Free's own boot runs on this action at the default priority, so this is the entry point for anything that extends the plugin.
add_action( 'shaped_recommend_loaded', function () {
// Safe here: WooCommerce is present and at a supported version,
// and Shaped Recommend's classes and public functions are available.
} );shaped_recommend_pro_loaded Pro
Fires after Pro has booted, which requires Free to be present and at or above Pro's minimum version. Use it for anything that depends on Pro being there.
shaped_recommend_register_shims
Fires once the plugin has loaded, for third-party compatibility shims: a page builder that swallows the_content, a theme that reorders the product summary hooks, and so on. Register workarounds here rather than patching the storefront renderer, so they stay in one inspectable place.
shaped_recommend_rebuild_snapshot
Fires when the published snapshot has to be rebuilt from the saved Recommendations, for example after a schema upgrade. The snapshot builder is the only subscriber. You'd fire it yourself only to force a republish; the POST /publish REST route does the same thing over HTTP.
Data actions
sprcm_recommendation_saved
Fires after a Recommendation is written. This is the publish seam: the snapshot builder hooks it, which is how there stays exactly one publish path.
/**
* @param int $stored The Recommendation's post ID.
* @param array $document The stored document.
* @param string $status The status it was stored with: 'live' (Active) or 'paused' (Inactive).
* @param string|null $previous The status it held before, or null on create.
*/
add_action( 'sprcm_recommendation_saved', function ( $stored, $document, $status, $previous ) {
if ( 'live' === $status && 'live' !== $previous ) {
// Something just went live.
}
}, 10, 4 );sprcm_recommendation_deleted
Fires after a Recommendation is deleted. The plugin uses it to drop the Recommendation from the priority order and republish. Its analytics rows are deliberately left alone.
/** @param int $id The deleted Recommendation's post ID. */
add_action( 'sprcm_recommendation_deleted', function ( $id ) { /* … */ } );sprcm_recommendation_restore_rejected
Fires when a restored revision fails save validation. WordPress has already written the restore by the time this runs, so what it tells you is that the document was not republished and needs a merchant's attention.
/**
* @param int $post_id The restored Recommendation.
* @param array $errors The validation findings.
*/
add_action( 'sprcm_recommendation_restore_rejected', function ( $post_id, $errors ) { /* … */ }, 10, 2 );sprcm_snapshot_rebuilt
Fires after the published snapshot has been replaced. Useful for cache eviction and instrumentation.
/**
* @param int $build_id The build just stored.
* @param int $previous The build it replaced.
* @param array $report Entries the build could not publish.
*/
add_action( 'sprcm_snapshot_rebuilt', function ( $build_id, $previous, $report ) {
if ( $report ) {
error_log( 'Shaped Recommend publish report: ' . wp_json_encode( $report ) );
}
}, 10, 3 );Dependent caches don't strictly need to listen: build_id is part of every cache key the plugin mints, so entries from a previous build are unreachable whether or not anything deletes them.
Filters
Tier and features
sprcm_capabilities
The tier gate map. Pro's whole tiering is one callback on this filter that widens Free's capability set. It receives and returns allowed tokens keyed by area (contexts, signals, filters, sorting, displays, locations, triggers, visibility_conditions, templates, coordination, analytics, analytics_ranges, features and filter_joins).
/** @param array<string, string[]> $capabilities The Free set. */
add_filter( 'sprcm_capabilities', function ( $capabilities ) {
// Narrowing works anywhere: hide the list display on this store.
$capabilities['displays'] = array_values( array_diff( $capabilities['displays'] ?? [], [ 'list' ] ) );
return $capabilities;
} );What to know before you touch it:
- Widening alone doesn't switch a feature on. A token survives only if registered code performs it (see
sprcm_register_implementation()). The exceptions are pure limits with no code of their own: filter joins, analytics ranges, the coordination caps and per-device columns. So adding'popup'todisplayson a Free-only store does nothing. - Narrowing always works. Anything can remove a token, except the two that are free by product decision: the
fbtsort and thefbttemplate are merged back in last, whatever the filter returns. - Merge, don't replace. Change the arrays you care about and return the rest untouched, so a second callback doesn't lose the first one's work.
- The result is never persisted. It's resolved per request, so there's no downgraded state to clean up when a callback goes away.
- The shape is re-established after filtering. Anything malformed is discarded rather than trusted.
The public function sprcm_capabilities() returns the resolved map.
Rendering
sprcm_card_template
Filters the absolute path of the product-card template, per product.
/**
* @param string $path Absolute template path.
* @param \WC_Product $product The product being drawn.
*/
add_filter( 'sprcm_card_template', function ( $path, $product ) {
if ( $product->is_type( 'variable' ) ) {
return get_stylesheet_directory() . '/shaped-recommend/card-variable.php';
}
return $path;
}, 10, 2 );For a blanket override, put card.php in your theme instead. See Templates & CSS.
sprcm_display_settings
Filters a placement's display settings at render time. The array carries heading, count, columns (desktop, tablet, mobile) and, for the bundle display, bundle_editable.
/**
* @param array $settings The snapshot's settings.
* @param ApprovedOffer $offer The offer being drawn
* (\ShapedPlugin\ShapedRecommend\Resolver\ApprovedOffer).
*/
add_filter( 'sprcm_display_settings', function ( $settings, $offer ) {
if ( wp_is_mobile() ) {
$settings['heading'] = 'Popular picks';
}
return $settings;
}, 10, 2 );This changes presentation only. The products have already been chosen and capped by the time it runs, so raising count here can't add products, and anything that isn't an array is ignored.
Candidates and sorting
sprcm_candidates
Filters one Recommendation's candidate product IDs before coordination. It's the documented seam for adding to a pool or narrowing it.
/**
* @param int[] $ids Candidate product IDs, pinned products first.
* @param int $rec_id The Recommendation's post ID.
* @param array $recommendation The snapshot's Recommendation row.
* @param RequestContext $context The request being resolved
* (\ShapedPlugin\ShapedRecommend\Resolver\RequestContext).
*/
add_filter( 'sprcm_candidates', function ( $ids, $rec_id, $recommendation, $context ) {
$discontinued = [ 101, 102 ];
return array_values( array_diff( $ids, $discontinued ) );
}, 10, 4 );Whatever you return is re-validated, so you can't inject a non-ID. You can remove a pinned product, which is deliberate. And every ID you return still goes through deduplication, the caps and the Recommendation Manager, like any other candidate.
sprcm_sort_affinity
Supplies the scores for the two order-history sorts, Frequently Bought Together (fbt) and Others Also Bought (oab). Free asks this filter and never reads the mined data itself. With nothing answering, the rule contributes nothing and the next sorting rule decides.
Pro answers it from the affinity store it mines. Pro
/**
* @param array<int, float> $values Scores by candidate ID, empty by default.
* @param string $type The sort type: 'fbt' or 'oab'.
* @param string $window The rule's window token, e.g. '90d'.
* @param int[] $ids The candidates being scored.
* @param RequestContext $context The request being resolved.
*/
add_filter( 'sprcm_sort_affinity', function ( $values, $type, $window, $ids, $context ) {
return $values;
}, 10, 5 );Return id => score, higher meaning more related. Leave a candidate out rather than scoring it zero if you have no data for it: zero says "unrelated" and ranks it last, while absent says "unmeasured" and lets the next rule decide.
Analytics and money
sprcm_currency_base_rate
The rate that converts an order's currency into the store's base currency, so revenue from different currencies can be added up. WooCommerce core has no exchange rates of its own, so a multi-currency store should answer this. Unanswered, the rate is 1.0, which makes base-currency totals approximate on a multi-currency store.
add_filter( 'sprcm_currency_base_rate', function ( $rate, $currency, $base = null, $order = null ) {
return my_fx_rate( $currency ); // A positive float.
}, 10, 4 );Give $base and $order default values, as above. Free calls it with all four arguments when attributing an order. Pro also calls it with three when it converts the cart total for the cart-value trigger, and then the third argument is null. Anything that isn't a positive number leaves the rate at 1.0.
sprcm_events_retention_days
How many days of raw view, click, add-to-cart and suppression events to keep. Default 90.
add_filter( 'sprcm_events_retention_days', fn () => 30 );Conversions and the daily rollups aren't affected. They're the attribution record and what the reports read, so shortening this changes how much the plugin stores, not what Analytics can answer.
sprcm_rollup_refresh_interval
The minimum gap, in seconds, between on-demand rebuilds of today's figures when someone opens a report. Default 60. Raise it on a very busy store to trade freshness for less work. 0 rebuilds on every read that finds new events. The nightly rollup job isn't affected either way.
REST hardening
sprcm_rate_limit
Per-route request limit for the three public storefront routes, per client, per minute.
| Route bucket | Default |
|---|---|
hydrate | 60 |
events | 120 |
dismiss | 20 |
add_filter( 'sprcm_rate_limit', function ( $limit, $route ) {
return 'hydrate' === $route ? 120 : $limit;
}, 10, 2 );Return 0 or less to switch limiting off for a route. That's a deliberate escape hatch for stores that rate-limit at their CDN or edge instead.
sprcm_trusted_proxy_headers
The $_SERVER keys that may carry the real client IP address, most trusted first. Empty by default, and that's the security property: any client can send X-Forwarded-For, so a rate limiter that believed it unconditionally could be dodged by sending a random value.
If your store sits behind a proxy, declare the header your infrastructure sets:
// Behind Cloudflare.
add_filter( 'sprcm_trusted_proxy_headers', fn () => [ 'HTTP_CF_CONNECTING_IP' ] );Without this, every shopper behind the same proxy shares one rate-limit bucket. A comma-separated value is read left-most first, and a value that isn't a valid IP address is ignored.
Import, migrations and snapshots
sprcm_import_max_bytes
The maximum size of an import file, in bytes. Default 1 MB.
add_filter( 'sprcm_import_max_bytes', fn () => 4 * MB_IN_BYTES );A store with hundreds of Recommendations may legitimately exceed the default. Raising it should be a deliberate act by someone who knows the file.
sprcm_document_migrations
The registered document migrations, keyed by the schema version being migrated from. Exposed so a site stuck mid-migration can be inspected or patched without editing the plugin. Free is the only package that migrates schema.
sprcm_snapshot_generator
The package versions stamped into the published snapshot and into every export file, as a debugging aid. Default [ 'free' => <Free version>, 'pro' => null ]. Pro fills in its own version through this filter. You shouldn't need to touch it.
Public functions
All in the global namespace, all available from shaped_recommend_loaded onward.
Capabilities and registration
sprcm_capabilities(): array
The resolved tier map for this request: the Free set, as any filter left it, narrowed to the tokens installed code can actually perform.
if ( in_array( 'statistics', sprcm_capabilities()['signals'] ?? [], true ) ) {
// Store Statistics is available here.
}Never persist the result. Call it, use it, discard it.
sprcm_register_source( SourceInterface $source ): bool
Registers a candidate source, the one supported way a new producer of recommendations enters the product. A source implements ShapedPlugin\ShapedRecommend\Resolver\SourceInterface: key() (its source_type token), signal() (the Recommendation signal it serves), can_produce(), reads_shopper_facts() and candidates().
add_action( 'shaped_recommend_loaded', function () {
sprcm_register_source( new My_Source() );
} );Returns false if key() is empty or longer than 16 characters (the width of the events table's source_type column, so a longer token would make the source unreportable), or if signal() is empty. A source registered for a signal that already has one replaces it. The builder only offers the signals the plugin knows (Rules and, with Pro, Store Statistics), so a source for a brand-new signal won't be selectable in the builder.
The contract a source signs:
- It contributes candidates through the resolver only. It never renders anything itself.
- It logs under its own
source_type, so its performance is separable in analytics. - It owns no tables. A source that needs storage proposes a schema change to Free rather than creating its own.
- It goes through the Recommendation Manager like every other source. There are no side channels, and that rule is the product.
- It says honestly whether it reads shopper data.
reads_shopper_facts()must returntruefor any document whose answer depends on who is asking (their cart, orders or browsing). Candidate pools are cached per page, not per shopper, so getting this wrong shows one shopper a pool computed for another. If you're unsure, returntrue.
sprcm_register_implementation( string $area, string $token, object $implementation ): bool
Registers the code that performs one capability token: a display, filter, sort, location, trigger, visibility condition, template, context or report. A token is available only while registered code answers it, whatever sprcm_capabilities says. This is how Pro ships its features.
Returns false, and changes nothing, when:
- the token is already answered (a second package claiming the same feature is a packaging mistake, so it's refused rather than silently replaced),
- the area is
signals(usesprcm_register_source()instead), or - the object doesn't implement the area's interface.
It implements tokens the plugin's registries already define. It doesn't add new options to the builder.
Admin and REST helpers
| Function | Returns |
|---|---|
sprcm_recommendation_admin_url( int $recommendation_id ): string | The admin URL that opens one Recommendation in the builder, or '' if the ID isn't a Recommendation or the current user can't manage them |
sprcm_settings_admin_url( string $tab = '' ): string | The Settings screen's URL, optionally on one tab (e.g. 'license') |
sprcm_rest_namespace(): string | sprcm/v1, so an add-on's own routes can't drift into a different namespace |
sprcm_rest_can_manage( WP_REST_Request $request ): true|WP_Error | The permission check every authoring route uses: sprcm_manage_recommendations plus a valid REST nonce. Pass it as your route's permission_callback |
sprcm_may_elevate(): bool | Whether the current user may perform the store-wide operations that need manage_options |
sprcm_tier_locked_recommendations(): array | Recommendations the tier stopped rendering in the last day, as [ 'id' => int, 'name' => string ] rows |
add_action( 'rest_api_init', function () {
register_rest_route( sprcm_rest_namespace(), '/my-report', [
'methods' => 'GET',
'callback' => 'my_report',
'permission_callback' => 'sprcm_rest_can_manage',
] );
} );Reporting reads
Report from these rather than from table names, so the event store's schema stays free to change.
| Function | Returns |
|---|---|
sprcm_conversions( array $query ): array | One row per attributed line: order_id, rec_id, product_id, source_type, revenue, currency, ts. Query by from + to (inclusive Y-m-d, site time), order_id and/or rec_id. A query with neither a range nor an order returns nothing |
sprcm_conversion_pairs( array $query ): array | One page of (order, Recommendation) pairs, newest first, each listing the products it earned. Needs from and to; takes rec_id, limit (default 25) and offset |
sprcm_orders_by_recommendation( string $from, string $to ): array | Distinct converted orders per Recommendation ID |
sprcm_attributed_revenue( WC_Order $order, array $product_ids ): array | gross (order currency) and gross_base (base currency, through sprcm_currency_base_rate), by the same rule the Analytics tiles use |
revenue in sprcm_conversions() is a snapshot taken at attribution time. For a figure that has to agree with the Analytics screen, which ignores cancelled orders and statuses your store excludes from its reports, ask sprcm_attributed_revenue().
Order windows and the affinity store
The affinity store holds mined "bought together" pairs. Free owns the table and these functions. Only Pro fills it, so on a Free-only store every read comes back empty. Pro
| Function | Returns |
|---|---|
sprcm_order_windows(): array | The order-history windows (7d, 14d, 30d, 90d, 6mo, 12mo, all), each with its length in seconds (all has null) |
sprcm_stats_cadence(): int | The stats_cache_hours setting in seconds. See REST API → Settings |
sprcm_affinity_partners( int $anchor, string $window, int $limit, int $min_co_purchases = 0 ): int[] | The best mined partners for a product, most significant first |
sprcm_affinity_scores_from( int $anchor, string $window, array $ids ): array | How strongly each candidate features among shoppers who bought the anchor |
sprcm_affinity_scores_towards( int $anchor, string $window, array $ids ): array | The reverse: how strongly the anchor features among shoppers who bought each candidate |
sprcm_affinity_has_data( string $window ): bool | Whether anything has been mined in that window |
sprcm_affinity_replace( string $window, array $anchors, array $rows ): int | Replaces a window's pairs for a set of anchors; returns rows written |
sprcm_affinity_clear(): void | Empties the store |
sprcm_affinity_clear() stops every mined recommendation
Until the next mining pass finishes, every Store Statistics block falls back to Rules. Never call it from a storefront request. It's what wp sprcm stats rebuild runs without --keep.
WooCommerce hooks the plugin uses
Worth knowing if you're debugging a conflict. When slot replacement hides WooCommerce's own sections, the plugin:
- removes core's callbacks for related products and up-sells (
woocommerce_after_single_product_summary) and cross-sells (woocommerce_cart_collaterals), - empties
woocommerce_product_get_upsell_idsfor the moment core draws up-sells, so a theme that draws them itself shows nothing either, - filters
woocommerce_cart_crosssell_ids, which also covers the Cart block, because it reads cross-sells through the Store API, and - drops the Cart block's cross-sells inner block through
render_block, heading and all.
It also filters woocommerce_product_add_to_cart_url, so add-to-cart links inside a recommendation block point at the shopper's page rather than at the REST request that drew them.
It never writes order or product data with direct SQL (WooCommerce CRUD objects only), and it declares compatibility with HPOS and the Cart & Checkout blocks.