Saltar al contenido
MovieMaster

Desarrolladores: plugins y themes

Hook reference (actions and filters)

14 min de lectura 12 apartados

En esta página

Hooks are the points where your code plugs into MovieMaster without touching the core. This page explains how they work and lists every hook the code fires, with its arguments and the exact moment it runs.

Actions and filters #

  • An action announces that something happened. Your functions run and whatever they return is ignored. Template actions (head, footer…) print HTML with echo.
  • A filter passes a value through every hooked function, in a chain. Each one receives the value (plus context arguments) and must return it, modified or not.
php
// Action: do something when a title is saved
add_action('title_saved', static function (array $title, bool $isNew): void {
    if ($isNew) {
        logger()->info('New title: ' . $title['title']);
    }
}, 10, 2);

// Filter: change a value and return it
add_filter('listing_per_page', static fn(int $n): int => 30);

Hook functions #

FunctionWhat it does
add_action(string $hook, callable $cb, int $priority = 10, int $acceptedArgs = -1)Hooks a function to an action.
add_filter(string $hook, callable $cb, int $priority = 10, int $acceptedArgs = -1)Hooks a function to a filter.
remove_action(string $hook, callable $cb, int $priority = 10): boolRemoves a function (same function and same priority it was added with).
remove_filter(string $hook, callable $cb, int $priority = 10): boolSame, for filters.
do_action(string $hook, mixed ...$args)Fires your own action.
apply_filters(string $hook, mixed $value, mixed ...$args): mixedPasses a value through your own filter.
has_action(string $hook): boolIs anyone listening to this hook?
did_action(string $hook): intHow many times it has already fired in this request.
current_filter(): ?stringThe hook currently running.
do_action_deprecated(string $hook, array $args, string $version, string $replacement = '')Fires a deprecated action: logs a warning only if someone is listening.
apply_filters_deprecated(string $hook, array $args, string $version, string $replacement = '')Same, for a deprecated filter.
hooks()The HookManager (methods add, remove, removeAll, doAction, applyFilters, has, did, current).

Priority #

Functions run from lowest to highest priority; with the same priority, in the order they were added. Use 5 to run before almost everything and 20 or higher to run after (for example, to tweak what another plugin already added).

Number of arguments #

With $acceptedArgs = -1 (the default) your function receives all of the hook's arguments. Pass a number and it receives only the first ones. Use this when you hook a plain PHP function or a method that doesn't accept extra arguments:

php
add_filter('seo_title', 'trim', 10, 1);

Removing another plugin's hook #

remove_action/remove_filter need the same function: a named function, a static method ([Class::class, 'method']), or the same object. An anonymous closure can't be removed from the outside; if you want others to be able to disable your behavior, offer it as a setting or expose your own filter:

php
if (apply_filters('my_plugin_show_box', true, $title)) {
    echo $box;
}

Your own hooks #

Always prefix the name with your slug (my_plugin_something) and document it in your README. If you change an already-published hook, keep the old one around for a while with do_action_deprecated('old', [$a, $b], '2.0.0', 'new'): it does nothing if nobody uses it, and logs a warning for those who do.

Live list from the console #

This page lists the core 0.9.x hooks. The exact list for your version is generated by the code itself:

bash
php bin/console.php hooks:list                    # name, action or filter, and number of uses
php bin/console.php hooks:list --where            # + first file:line where it fires
php bin/console.php hooks:list --type=filter --json

Boot, routes, and console #

HookTypeArgumentsWhen
bootedaction$appConfig, container, and database ready, before plugins load: a plugin never sees it. That's what init is for.
routesaction$router, $appRoute registration. $plugin->route() hooks here with priority 5.
initaction$appCore, plugins, and theme loaded, routes registered. The place for anything that needs all of the above.
terminateaction$requestAt the end of the request, after the response has been sent. Good for work that shouldn't delay the page.
migrateaction$migrator, $iophp bin/console.php migrate, after the core's migrations.
console_commandsfilter$commands (name => class)Add commands to bin/console.php. See creating plugins.
cronaction$cronEvery cron run (every minute). Shortcut: $plugin->cron('minute', fn).
cron_hourlyaction—Once an hour, after the core's maintenance. Shortcut: $plugin->cron('hourly', fn).
cron_dailyaction—Once a day, after the core's maintenance (cleanup, license, updates). Shortcut: $plugin->cron('daily', fn).
queue_handlersfilter$handlers (type => callable|class)Queue handlers. Shortcut: $plugin->job($type, $handler).

Public site templates #

Template actions are fired by the theme with @hook('name'). Your function prints HTML with echo; escape any data-derived value with e().

HookTypeArgumentsWhere
template_datafilter$data, $templateBefore rendering a page: add or change template variables.
before_renderaction$template, $dataRight before rendering. Useful for remembering $template and deciding what to print in head.
template_pathfilter$template, $templateChange which template is used ('title' → 'my-plugin::detail').
body_classfilter$class ('tpl-<template>')Classes on the <body>. Append with $class . ' my-class'.
headaction—Inside <head>. This is where meta tags, the canonical, the JSON-LD, and your inline CSS go.
body_openaction—Right after <body>.
nav_itemsaction—Inside the main <nav>, after the theme's own links. Prints <a> tags.
before_contentaction—Before the main content (<main>).
after_contentaction—After the main content.
footeraction—In the footer.
body_closeaction—Right before </body>. The place for your <script type="module">.
player_beforeaction—On the detail page and the episode page, before the player.
player_afteraction—On the detail page and the episode page, after the player.
commentsaction—Slot for the comments box in title.tpl and episode.tpl. Only fired by a theme that declares comments@1.
account_sectionsaction—On the Members plugin's "My Account" page, to add sections.
home_railsfilter$railsHome page rails. See the shape below.
listing_per_pagefilter$perPageItems per page in listings (minimum 6).
related_limitfilter$limit, $titleHow many related titles to look for.
related_titlesfilter$titles, $titleThe final list of related titles for a detail page.
embed_htmlfilter$html, $sourceThe HTML of a video server (the iframe the facade creates).
ad_scripts_codefilter$code, $keyCode of an ad block from Admin → Ad scripts. Return '' to not print it.
search_suggestionsfilter$out, $qSearch box suggestions: ['titles' => [], 'people' => [], 'genres' => []].

Shape of a home_rails item:

php
$rails['my_rail'] = [
    'title' => 'Recommended',              // visible text
    'url' => url('/movies') . '?sort=rating', // "view all" link (optional)
    'items' => $titles,                    // TitleRepository rows; a rail with no items isn't rendered
    'style' => 'cards',                    // cards | top10 | episodes
];

Content #

HookTypeArgumentsWhen
title_savedaction$title, $isNewA movie or series was created or edited ($title = the row already saved).
title_deletedaction$titleA title was deleted (its URLs' 410 has already been written).
title_queryfilter$query, $filtersThe title listing query, before it runs. Add conditions via the builder.
sources_savedaction$titleId, $episodeIdVideo sources saved ($episodeId is null for a movie).
person_savedaction$personA person was created or edited.
person_deletedaction$idA person was deleted.
term_savedaction$term, $taxonomyA genre, tag, or custom term was saved.
term_deletedaction$termA term was deleted.
taxonomy_labelfilterucfirst($taxonomy), $taxonomyThe admin panel name of a custom taxonomy.
taxonomy_url_prefixfilter$prefix, $taxonomyThe URL word for a custom taxonomy.
url_key_changedaction$kind, $id, $old, $newA season's or episode's URL word changed ($kind = season or episode). The 301s have already been created.
availability_changedaction$id, $type, ['title' => bool, 'episodes' => int[]]A title or episodes became available (useful for notifying subscribers).
media_uploadedaction$mediaAn image was uploaded and processed.
media_deletedaction$mediaAn image was deleted along with all its variants.
media_shared_fetchfilternull, $slotBefore downloading the image for a slot: return an existing media row to reuse it (media library shared across sites).
media_offload_pathsfilter[], $slot, $idsAdmin → Catalog → free disk space: TMDB paths ([id => '/abc.jpg']) of the images that can be served from elsewhere.
content_purgedaction$tagsAfter purging cache tags.
purge_tagsfilter$tagsThe tags to purge, before doing so. Add your own.
page_cache_purgedaction$tags, $pathsAfter clearing pages from the static page cache (['*'] = all of it). Use this to notify a CDN.
page_cache_bypassfilterfalse, $requestReturn true to skip storing this response in the static page cache.

Video sources and player #

HookTypeArgumentsWhat for
source_languagesfilter$languagesAudio languages for sources: ['latino', 'castellano', 'subtitulado', 'english', 'original'].
source_language_codefilter$code, $languageShort code for the language tab (LAT, ESP, SUB…).
source_default_languagefilter$language, $siteLangThe source language that opens first.
player_api_urlfilter$urlBase URL of the player's resolver API (the one read from data-api-base).
player_api_languagesfilter$languages, $siteLangLanguages requested from the API based on the site language.
player_api_sourcesfilter$grouped, $title, $episodeSources grouped by language, as received by the player.
player_api_coversfiltertrue, $title, $episodeReturn false to not use the API for that title or episode.
player_source_allowedfiltertrue, $source, $title, $requestMoney Player asks before playing: false blocks the source (used by Members VIP).
money_player_templatesfilter['title', 'episode']Templates where Money Player is active.
money_player_resolversfilter$classesClasses implementing ResolverInterface to play a host inside the built-in player.

SEO, sitemaps, and PWA #

HookTypeArgumentsWhat for
seo_titlefilter$titleThe page's final <title>.
seo_schemafilter$graph, $ctx, $dataThe JSON-LD nodes (@graph). Add nodes to the array; never print another <script type="application/ld+json">.
seo_metafilter$seo, $ctx, $dataThe full PageSeo object (title, description, canonical, robots, image, alternates…).
sitemap_indexfilter$items ('/path.xml' => lastmod)Entries in the sitemap index. Add your own.
sitemap_customfilternull, $type, $chunkContent of a non-core sitemap (/sitemap-<type>-<n>.xml or /sitemap-<type>.xml, $type lowercase letters only): return the XML or null (404).
robots_txtfilter$textThe generated robots.txt.
indexnow_requestfilternull, $bodySubmission to IndexNow: return an HTTP status code (int) if you send it yourself.
pwa_manifestfilter$dataThe manifest.webmanifest.
pwa_iconsfilter$iconsPWA icons.

Values of $ctx in seo_schema and seo_meta, with what $data carries:

$ctx$data
homepage
movie, seriestitle
seasontitle, season
episodetitle, episode
genre, tag (and custom taxonomies)term, page
personperson, page
pagepage (the static page)
searchq
movies, series_list, year, genres, tags, people (listings)page
php
add_filter('seo_schema', static function (array $graph, string $ctx, array $data): array {
    if ($ctx === 'movie') {
        $graph[] = ['@type' => 'Review', 'itemReviewed' => ['@id' => url($data['title']['url'], true) . '#movie'], /* … */];
    }
    return $graph;
});

Settings, users, and extensions #

HookTypeArgumentsWhen
settings_groupsfilter$groups (key => [label, fields[]])Settings groups. This is how plugin settings get in ($plugin->setting() does it for you).
settings_before_savefilter$save, $groupAlready-validated values (key => value) before they're saved.
settings_savedaction$group, $saveAfter a settings group is saved (Admin → SEO fires 'seo', ['tab' => …]).
user_loginaction$userSuccessful admin panel sign-in.
login_failedaction$login, $ipFailed sign-in attempt.
role_capabilitiesfilter$caps, $roleCapabilities of a role. See admin pages.
mail_sendfilternull, $messageReturn true if you sent the email yourself (your own SMTP, an API) or false if it failed; null lets the core send it. $message = to, subject, body, from, from_name.
extension_installedaction$type, $slugAfter installing a plugin or theme zip.
extension_updatedaction$type, $slugAfter updating one already installed.
extension_activatedaction$type, $slugAfter activating a plugin or switching themes.
extension_deactivatedaction$type, $slugAfter deactivating it.
extension_uninstalledaction$type, $slugAfter deleting the plugin and its data.
update_beforeaction$old, $newCore update, before files are replaced.
update_afteraction$old, $newCore update finished (migrations and cache included).

Admin panel #

Details and examples in admin pages.

HookTypeArgumentsWhat for
admin_menufilter$itemsThe admin panel's menu entries.
admin_routesaction$routerYour own routes inside /admin (with its session and CSRF).
admin_headaction—Inside the admin panel's <head>. Never reaches the public site.
admin_footeraction—Before the admin panel's </body>.
admin_dashboard_widgetsfilter$widgetsDashboard cards: ['title' => …, 'html' => …].
admin_dashboard_status_cardsfilter$cardsCards in the dashboard's status block. Same shape.
admin_disk_min_free_gbfilternullMinimum free GB before warning about a full disk.
admin_onboarding_stepsfilter$items, $stats, $healthDashboard's short list of first steps: [key, done, link, label?].
admin_onboarding_itemsfilter$itemsFull list of Admin → Getting started.
admin_search_resultsfilter$items, $type, $qResults from the admin panel's search box.
admin_settings_links_forfilter[], $fieldKeyLinks [url, label] next to a settings field.
admin_settings_fieldaction$fieldKeyYour own HTML below a settings field.
admin_titles_index_topaction$typeAbove the Movies or Series table (movie/series).
admin_title_form_topaction$type, $titleAt the top of a title's form ($title is null when creating).
admin_title_actionsaction$titleButtons next to the title on its edit page.
admin_catalog_panelaction—On Admin → Catalog, below the catalog form.

Import and catalog #

HookTypeArgumentsWhen
tmdb_importedaction$id, $type, $tmdbId, $dataA title was imported from TMDB (TMDB Import plugin).
tmdb_season_importedaction$titleId, $tmdbId, $numberA season was imported from TMDB.
catalog_importerfilternullWho imports the lines that request TMDB: ['job' => 'tmdb.import', 'ready' => bool].
catalog_importedaction$id, $type, $tmdbIdA title was created from the Hub's pre-loaded catalog.
catalog_syncedaction$scope, $versionA full catalog sync finished.
csv_import_resolve_titlefilternull, $type, $rowCSV import: return the id of an existing title for a row.

Hooks from bundled plugins #

These are fired by plugins that ship with the core; they only exist if the plugin is active.

HookPluginTypeArgumentsWhen
member_registeredMembersaction$memberA member signed up.
member_blockedMembersaction$memberA member was blocked.
member_deletedMembersaction$idAn account was deleted (by the member or the admin).
comment_postedCommentsaction$commentA comment was submitted.
comment_statusCommentsaction$id, $statusA comment was approved, rejected, or marked as spam.
comment_moderationCommentsfilter$status, $body, $memberInitial status of a new comment: approved, pending, or spam (any other value becomes pending).
vip_payment_receivedMembers VIPaction$id, $memberA member submitted a payment for review.
vip_payment_approvedMembers VIPaction$paymentId, $memberId, $untilPayment approved; VIP until $until.

Recipes #

Change the number of related items only for series:

php
add_filter('related_limit', static fn(int $n, array $t): int => $t['type'] === 'series' ? 18 : $n, 10, 2);

Hide titles with a given tag from listings:

php
add_filter('title_query', static function ($q, array $filters) {
    if (empty($filters['term_id'])) {   // they're still shown on that tag's own page
        $q->whereNotIn('titles.id', db()->table('title_terms')->select('title_id')->where('term_id', 42));
    }
    return $q;
});

Notify a CDN when the cache is purged:

php
add_action('page_cache_purged', static function (array $tags, array $paths): void {
    app(MyPlugin\Cdn::class)->purge($paths === ['*'] ? null : $paths);   // better to queue it with $plugin->jobs()
});

Add your own sitemap:

php
add_filter('sitemap_index', static function (array $items): array {
    $items['/sitemap-events-1.xml'] = db()->table('events')->max('updated_at');
    return $items;
});
add_filter('sitemap_custom', static function (?string $xml, string $type, int $chunk): ?string {
    return $type === 'events' ? app(MyPlugin\Sitemap::class)->xml($chunk) : $xml;
});

¿Te quedó alguna duda?

Escríbenos y te ayudamos con tu caso.

Hablar con nosotros
¿Hablamos?