Back to Main Site

Hooks & Filters Reference: Complete Developer Guide

Last updated on Jun 24, 2026 02:02

Hooks & Filters Reference

Audience: Developer — Requires PHP / Laravel knowledge. Category: Technical Reference — Technical documentation for integration developers.

What You Will Learn

  • Understand the Action vs Filter mechanism in PolyCMS

  • Look up hook names, parameters, and dispatch locations

  • Register hooks from theme functions.php and module ServiceProvider

  • Use priority to control the order of execution

  • Apply practical use-cases for each hook group

1. Introduction to the Hook System

PolyCMS uses a WordPress-like Hook/Filter system, built natively on Laravel:

  • Action (Hook::doAction): Executes side-effects (logging, sending emails, syncing data). No return value needed.

  • Filter (Hook::applyFilters): Receives a value, modifies it, and must return the modified value.

Basic Syntax

use App\Facades\Hook;

// Register an Action
Hook::addAction('order_completed', function ($order) {
    Mail::to($order->user)->send(new OrderCompletedMail($order));
}, priority: 10);

// Register a Filter
Hook::addFilter('post.default_image', function (?string $imageUrl, $post) {
    if ($post?->categories->contains('slug', 'news')) {
        return '/images/news-default.jpg';
    }
    return $imageUrl;
}, priority: 10);

2. Content & Posts

Filters

Hook Parameters Description
post.default_image $imageUrl, $context Default image when a post does not have a featured image
post.frontend_url $url, $post Customize the public URL of a post
post.content.render $html, $post Filter the post HTML content before returning to the API
post.query.builder $query, $request Modify the Eloquent query for the post list
category.frontend_url $url, $category Customize the public URL of a category
content.render.blocks $blocks Filter the block array before rendering
content.render.html $html, $blocks Filter the final output HTML
content.render.block.{type} $html, $block Render or override a specific block type

Actions

Hook Parameters Description
tag.saved $tag, $context Triggered after a tag is created/updated
tag.deleted $tag, $context Triggered after a tag is deleted
category.saved $category, $context Triggered after a category is created/updated
category.deleted $category, $context Triggered after a category is deleted

Practical Use-cases

UC1 — Category-specific default thumbnail: Keep a specific default thumbnail for each category when a post does not have a featured image:

Hook::addFilter('post.default_image', function (?string $url, $post) {
    if ($post?->categories->contains('slug', 'tech')) return '/images/defaults/tech.jpg';
    if ($post?->categories->contains('slug', 'lifestyle')) return '/images/defaults/lifestyle.jpg';
    return $url; // fallback to admin setting
});

UC2 — Wiki URL structure: Demote/change a post URL structure from /posts/slug to /docs/slug for a wiki-style layout:

Hook::addFilter('post.frontend_url', function ($url, $post) {
    return ($post->type === 'wiki') ? '/docs/' . $post->slug : $url;
});

UC3 — Auto-inject inline advertisements: Automatically insert ad banner blocks after the 3rd paragraph of a post:

Hook::addFilter('content.render.html', function (string $html) {
    $adBanner = '<div class="ad-inline">Advertisement</div>';
    $parts = explode('</p>', $html, 4);
    if (count($parts) > 3) {
        $parts[2] .= '</p>' . $adBanner;
        return implode('</p>', $parts);
    }
    return $html;
});

3. Media Library

Filters

Hook Parameters Description
media.upload.file $file, $data Modify the uploaded file before processing
media.upload.data $data, $file Modify upload metadata
media.create.data $mediaData, $file Modify media record attributes before saving to DB
media.delete.should $shouldDelete, $media Security gate: return false to block media deletion
media.url $url, $media Rewrite URL (e.g., to redirect to CDN)

Actions

Hook Parameters Description
media.uploaded $media, $file, $data Triggered after a successful upload
media.deleting $media Triggered before deletion
media.deleted $media Triggered after deletion

Practical Use-cases

UC1 — CDN URL Rewriting: Integrate with Cloudflare R2 or Amazon S3, automatically converting local storage paths to CDN URLs:

Hook::addFilter('media.url', function (string $url, $media) {
    return str_replace('/storage/', 'https://cdn.mysite.com/', $url);
});

UC2 — Protect Critical System Assets: Prevent accidental deletion of any image currently in use as the site logo:

Hook::addFilter('media.delete.should', function (bool $allow, $media) {
    $logoUrl = get_option('site_logo', null, 'general');
    return ($media->url === $logoUrl) ? false : $allow;
});

UC3 — Auto-optimize Images on Upload: Dispatch background queues to generate lightweight WebP images from standard uploads:

Hook::addAction('media.uploaded', function ($media, $file) {
    if (str_starts_with($media->mime_type, 'image/')) {
        dispatch(new ConvertToWebpJob($media));
    }
});

4. E-Commerce — Orders & Refunds

Actions

Hook Parameters Description
order_status_updated $order, $oldStatus, $newStatus Triggered when order status changes
order_completed $order Triggered when an order is successfully completed
order.refund.processing $order, $validated Triggered before processing a refund
order.refund.completed $order, $result Triggered after a successful refund
order.refund.succeeded $order, $result, $validated, $userId API refund succeeded
order.refund.failed $order, $validated, $exception, $userId API refund failed

Filters

Hook Parameters Description
order.refund.preview.result $preview, $order, $input Modify the refund preview data

Practical Use-cases

UC1 — Telegram Notification for New Orders:

Hook::addAction('order_status_updated', function ($order, $old, $new) {
    if ($old === 'pending' && $new === 'processing') {
        TelegramBot::send(" Order #{$order->code} has been confirmed!");
    }
});

UC2 — Loyalty Reward points on Order Completion:

Hook::addAction('order_completed', function ($order) {
    if ($order->user_id) {
        $points = (int) floor($order->total / 10); // 1 point per $10 spent
        LoyaltyService::addPoints($order->user_id, $points, "Order #{$order->code}");
    }
});

UC3 — Audit Logging for Failed Refunds:

Hook::addAction('order.refund.failed', function ($order, $data, $exception, $userId) {
    AuditLog::create([
        'action' => 'refund_failed',
        'order_id' => $order->id,
        'user_id' => $userId,
        'reason' => $exception->getMessage(),
    ]);
});

5. E-Commerce — Cart, Shipping, Tax, Inventory

Filters

Hook Parameters Description
cart.totals $totals, $cart Modify cart totals
shipping.calculate_cost $cost, $method, $cart Override shipping costs
shipping.available_methods $methods, $address, $cart Filter shipping methods based on address and cart contents
tax.calculated $result, $subtotal, $address Override calculated tax result
inventory.is_stockable_product $default, $product, $context Check if a product tracks inventory levels
review.can_submit $allowed, $user, $product Security gate: allow a user to submit a review?

Actions

Hook Parameters Description
cart.item.added $item, $cart Triggered after an item is added to the cart
cart.item.updated $item, $oldQty, $newQty Triggered after an item quantity changes
cart.item.removed $item, $cart Triggered after an item is removed
cart.cleared $cart Triggered after clearing the cart
cart.merged $userCart, $guestCart Triggered when guest cart merges into authenticated user cart
review.submitted $review Triggered after submitting a review
review.approved $review Triggered after approving a review
review.rejected $review Triggered after rejecting a review

Practical Use-cases

UC1 — Free Shipping for Orders over $100:

Hook::addFilter('shipping.calculate_cost', function ($cost, $method, $cart) {
    $subtotal = collect($cart->items)->sum(fn($i) => $i->price * $i->quantity);
    return ($subtotal >= 100) ? 0 : $cost;
});

UC2 — Block Reviews if User has Not Purchased the Product:

Hook::addFilter('review.can_submit', function (bool $allowed, $user, $product) {
    $hasPurchased = Order::where('user_id', $user->id)
        ->where('status', 'completed')
        ->whereHas('items', fn($q) => $q->where('product_id', $product->id))
        ->exists();
    return $hasPurchased;
});

UC3 — Facebook Pixel Tracking for AddToCart Event:

Hook::addAction('cart.item.added', function ($item, $cart) {
    session()->push('fb_pixel_events', [
        'event' => 'AddToCart',
        'product_id' => $item->product_id,
        'value' => $item->price,
    ]);
});

6. E-Commerce — Payment Gateways

Filters

Hook Parameters Description
payment.gateway.config_schema $schema, $gateway Extend schema configuration fields for a gateway

Practical Use-case: Add a custom field to Bank Transfer gateway:

Hook::addFilter('payment.gateway.config_schema', function ($schema, $gateway) {
    if ($gateway->code === 'bank_transfer') {
        $schema['branch_code'] = [
            'type' => 'text', 'label' => 'Branch Code', 'required' => false,
        ];
    }
    return $schema;
});

7. Theme & Appearance

Filters

Hook Parameters Description
theme.view.data $data, $viewName Inject/modify view variables for any Blade template
theme.template.resolve $viewName, $templateTheme, $entityType, $entity Override matching Blade views
theme.template.registry $templates, $viewType Register new page templates
theme.options.values $options Filter loaded theme option values
theme.options.css_vars $cssVars, $themeOptionValues Modify custom CSS properties
theme.breadcrumbs.post $breadcrumbs, $post Filter post breadcrumbs
theme.breadcrumbs.product $breadcrumbs, $product Filter product breadcrumbs
theme.show_page_header $show, $page Toggle visibility of the page header
frontend.topbar.banners $banners Inject top bar promotional banners
themes.list $themes Filter list of available themes in admin

Actions

Hook Parameters Description
theme.activated $theme Triggered when a theme is activated
theme.main.changed $theme, $oldMainTheme Triggered when changing main themes
theme.installing $file Triggered before extracting theme ZIP
theme.activating $slug, $type, $mode Triggered before activating a theme
theme.deactivating $slug Triggered before deactivating a theme
theme.deleting $theme Triggered before deleting a theme
cms_head (none) Output hook inside layout <head> tag

Practical Use-cases

UC1 — Inject Promo Banner from a Module:

Hook::addFilter('frontend.topbar.banners', function (array $banners) {
    $banners[] = [
        'text' => ' Flash Sale — 30% Off Today!',
        'url' => '/sale',
        'bg_color' => '#ff4444',
    ];
    return $banners;
});

UC2 — Google Analytics Head Injection:

Hook::addAction('cms_head', function () {
    $ga = get_option('google_analytics_id', null, 'seo');
    if ($ga) {
        echo "<script async src='https://www.googletagmanager.com/gtag/js?id={$ga}'></script>";
    }
});

UC3 — Load Popular Posts Sidebar Variable:

Hook::addFilter('theme.view.data', function ($data, $viewName) {
    if ($viewName === 'posts.index') {
        $data['popular_posts'] = Post::orderBy('views', 'desc')->limit(5)->get();
    }
    return $data;
});

8. Settings & Configuration

Filters

Hook Parameters Description
settings.defaults $defaults, $settingsService Extend or override base settings definitions
settings.media.drivers $drivers Register new media storage drivers
settings.permalinks.structure $structure, $settingsService Filter system permalinks

Actions

Hook Parameters Description
setting.updating $key, $value, $group, $type Triggered before saving a setting
settings.saved $payload Triggered after settings are saved

Practical Use-cases

UC1 — Register Custom Settings Section via Module:

Hook::addFilter('settings.defaults', function ($defaults) {
    $defaults['mymodule'] = [
        'mymodule_api_key' => [
            'key' => 'mymodule_api_key', 'value' => '', 'type' => 'text',
            'label' => 'API Key', 'description' => 'Enter your API key',
        ],
    ];
    return $defaults;
});

UC2 — Clear Route Cache on Permalinks Update:

Hook::addAction('settings.saved', function ($payload) {
    if (($payload['group'] ?? '') === 'permalinks') {
        Artisan::call('route:clear');
        Cache::tags('routes')->flush();
    }
});

9. Users, Roles & Auth

Filters

Hook Parameters Description
user.resource.to_array $data, $user, $request Extend user API resource output
auth.login.pre_token $response, $user, $request Intercept login lifecycle (e.g., for Multi-Factor Auth)

Actions

Hook Parameters Description
user.creating / user.updating / user.deleting `$user $data`
role.creating / role.updating / role.deleting / role.cloning `$role $data`

Practical Use-cases

UC1 — Multi-Factor Authentication Interceptor:

Hook::addFilter('auth.login.pre_token', function ($response, $user, $request) {
    if ($user->hasRole('admin') && !$request->filled('otp_code')) {
        return response()->json(['requires_2fa' => true, 'user_id' => $user->id], 403);
    }
    return $response; // null = continue token generation
});

UC2 — Welcome Email on User Signup:

Hook::addAction('user.creating', function ($data) {
    dispatch(new SendWelcomeEmail($data['email'], $data['name']));
});

10. SEO

Filters

Hook Parameters Description
seo.canonical_url $url Override canonical URLs
seo.site_favicon $iconUrl Override favicon paths

Practical Use-case — Canonical URL for Multilingual setups:

Hook::addFilter('seo.canonical_url', function (string $url) {
    $locale = app()->getLocale();
    if ($locale !== 'en') {
        return url("/{$locale}" . parse_url($url, PHP_URL_PATH));
    }
    return $url;
});

11. Widgets

Filters

Hook Parameters Description
widget.render.instance $instance Modify widget instance settings before rendering
widget.render.{widget_type} $widget Modify specific widget data
widget.area.render.instances $instances, $area Filter widget instances loaded within an area
widget.render.output $html, $instance Filter a single widget's HTML output
widget.area.render.output $html, $area Filter rendering output of a widget area
widgets.types $widgets Filter list of registered widget types

Actions

Hook Parameters Description
widgets.register_types $widgetManager Register new widget types
widgets.register_areas $widgetManager Register new widget areas

Practical Use-case — Register a "Store Map" widget type:

Hook::addAction('widgets.register_types', function ($manager) {
    $manager->registerType('store_map', [
        'label' => 'Store Map',
        'description' => 'Google Maps showing store locations',
        'fields' => [
            'api_key' => ['type' => 'text', 'label' => 'Google Maps API Key'],
            'lat' => ['type' => 'text', 'label' => 'Latitude'],
            'lng' => ['type' => 'text', 'label' => 'Longitude'],
        ],
        'view' => 'widgets.store-map',
    ]);
});

12. Admin Navigation & Editor

Filters

Hook Parameters Description
topbar.menu.items $items, $request, $user Add/remove items from frontend admin bar
topbar.menu.should_show $show, $user Toggle visibility of frontend top admin bar
admin.editor.panels $panels, $type, $user Add custom panels to the block editor sidebar

Actions

Hook Parameters Description
admin.menu.build (none) Fired when assembling sidebar navigation menu
topbar.menu.context $request, $user Fired when frontend admin bar is initialized

Practical Use-case — Add custom SEO status menu item to top bar:

Hook::addFilter('topbar.menu.items', function (array $items, $request, $user) {
    $items[] = [
        'key' => 'seo_score',
        'label' => 'SEO Score',
        'icon' => 'chart-bar',
        'url' => '/admin/seo/score',
        'position' => 50,
    ];
    return $items;
});

13. Modules

Filters

Hook Parameters Description
module.resource.meta $meta, $moduleData Extend module metadata details
modules.list $modulesArray Filter listed modules in admin
product.query.builder $query, $request Modify product Eloquent list queries

Actions

Hook Parameters Description
module.activating $moduleKey, $module Triggered before activating a module
module.deactivating $moduleKey, $module Triggered before deactivating a module
module.deleting $moduleKey, $module Triggered before deleting a module
module.installing $uploadedFile Triggered on uploading new module ZIPs

Practical Use-case — Auto-run migrations on module activation:

Hook::addAction('module.activating', function ($moduleKey, $module) {
    Artisan::call('migrate', [
        '--path' => "modules/Polyx/{$moduleKey}/database/migrations",
        '--force' => true,
    ]);
});

14. System Bootstrap

Actions

Hook Parameters Description
roles.register_permissions $permissionRegistry Register new system permissions
register_email_templates $emailTemplateManager Register core email templates
layout.register_assets $layoutAssetManager Register custom admin/frontend layout assets
routes.frontend.register (none) Inject custom frontend routes

Practical Use-case — Module registers custom capabilities/permissions:

Hook::addAction('roles.register_permissions', function ($registry) {
    $registry->register('manage analytics', 'Analytics', 'View and manage analytics dashboard');
    $registry->register('export reports', 'Analytics', 'Export analytics reports to CSV');
});

Related Articles


PolyCMS is an open-source content management system for modern web applications, inspired by the WordPress plugin and theme ecosystem but built on top of the Laravel framework. It is designed to provide a complete foundation for content publishing, e-commerce, multi-language support, and extensible module architecture — powered by a Vue 3 admin panel with data served entirely through RESTful APIs.

Whether you're building a blog, a documentation site, an online store, or a multi-tenant SaaS platform, PolyCMS aims to give you a comprehensive starting scaffold so you can ship quickly and extend easily through integrated modules and themes. In particular, themes in PolyCMS follow a multi-theme architecture — one Main theme and an unlimited number of Sub themes can run side by side on the same installation.

We hope this ready-made foundation proves useful for building your next website, blog, or web app, saving you from having to start completely from scratch.