Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 30 ยท Hooks

Common Front Office Hooks

Learn the PrestaShop hooks you use most on the storefront: displayHeader, actionFrontControllerSetMedia, displayProductAdditionalInfo and displayShoppingCart.

A shop's storefront is built from templates, and almost every template leaves openings for modules. These openings are the front office hooks. If you want a badge under the product price, a progress bar in the cart, or a stylesheet on one page only, you pick the right hook, write a small method, and PrestaShop calls it at the right moment.

This lesson covers the four hooks you will meet in nearly every storefront module: displayHeader, actionFrontControllerSetMedia, displayProductAdditionalInfo and displayShoppingCart. You also learn how hook parameters work and how to register CSS and JavaScript the modern way. It builds on Hooks: How Modules Plug In.

All PrestaShop code in the read-only blocks below needs a running shop, so it cannot execute on this site. The live examples are runnable PHP stand-ins that mimic the idea: an asset manager, a hook dispatcher and a page. The stand-ins are not PrestaShop code; they show the shape of the mechanism.

Display hooks and action hooks, in the storefront

Remember the two families. A display hook returns a string of HTML that is placed where the hook sits in a template. An action hook returns nothing useful: it tells your module that something is happening so you can react. On the storefront:

  • displayHeader is a display hook placed inside the <head> of the page layout.
  • actionFrontControllerSetMedia is an action hook fired while the front controller prepares its assets. You use it to register CSS and JavaScript.
  • displayProductAdditionalInfo and displayShoppingCart are display hooks placed in the product page and cart page templates.

Which templates actually contain a hook call is decided by the theme. A hook only produces output if the active theme calls it, which is why the same module can look different (or empty) in another theme. Always open the theme's template and search for {hook h='...'} when something does not show up.

flowchart TD
    A["Request: /product page"] --> B["Front controller starts"]
    B --> C["actionFrontControllerSetMedia<br/>modules register CSS and JS"]
    C --> D["Theme layout renders"]
    D --> E["displayHeader<br/>inside head"]
    D --> F["Page template"]
    F --> G["displayProductAdditionalInfo<br/>inside product block"]
    F --> H["displayShoppingCart<br/>on the cart page"]

Assets are registered first; the display hooks are called later while the templates render.

Registering a hook

A module attaches itself to hooks when it is installed. The method name tells PrestaShop what to call: hook followed by the hook name with its first letter capitalized.

PHP
<?php
// modules/acmebadge/acmebadge.php (excerpt, read-only)
if (!defined('_PS_VERSION_')) {
    exit;
}

class Acmebadge extends Module
{
    public function install(): bool
    {
        return parent::install()
            && $this->registerHook('actionFrontControllerSetMedia')
            && $this->registerHook('displayProductAdditionalInfo')
            && $this->registerHook('displayShoppingCart');
    }

    public function hookDisplayProductAdditionalInfo(array $params): string
    {
        return '<p class="acmebadge">Free returns</p>';
    }
}

If a hook is missing in the registerHook list, the method is never called, even when it exists. Registering also happens only at install time: if you add a new hook to an installed module, you must re-register it (reset the module, or write an upgrade script, which you meet in Tables, Installers and Upgrades).

Assets: actionFrontControllerSetMedia

Older modules put <link> and <script> tags straight into displayHeader. That works but bypasses PrestaShop's asset pipeline, so the files cannot be combined, moved to the bottom of the page or minified by the shop's CCC (combine, compress, cache) settings. The recommended way is to register the files with the controller from actionFrontControllerSetMedia:

PHP
<?php
// read-only: needs a running PrestaShop
public function hookActionFrontControllerSetMedia(array $params): void
{
    // Only load on the product page.
    if ($this->context->controller->php_self !== 'product') {
        return;
    }

    $this->context->controller->registerStylesheet(
        'module-acmebadge-style',
        'modules/' . $this->name . '/views/css/badge.css',
        ['media' => 'all', 'priority' => 150]
    );

    $this->context->controller->registerJavascript(
        'module-acmebadge-script',
        'modules/' . $this->name . '/views/js/badge.js',
        ['position' => 'bottom', 'priority' => 150]
    );
}

The pieces:

  • The first argument is a unique id. Use module-<modulename>-<purpose> so two modules never clash; registering the same id twice replaces the first.
  • The path is relative to the shop root. For a file hosted elsewhere, pass 'server' => 'remote' and a full URL.
  • priority orders files: lower numbers load earlier, and the default is 50. Files registered by the theme sit around 50 and 100, so 150 puts yours after them and lets your CSS win ties.
  • JavaScript position is head or bottom; scripts at the bottom do not block rendering.
  • $this->context->controller->php_self is the page name (index, category, product, cart, order...). Checking it keeps your assets off pages that do not need them, which matters for speed (Performance and Caching).

The hook receives an empty (or almost empty) $params array: everything you need comes from $this->context.

displayHeader

displayHeader is the place for things that must be inside <head> but are not CSS or JS files: a meta tag, a canonical link, an inline JSON-LD block, or a small inline style.

PHP
<?php
// read-only
public function hookDisplayHeader(array $params): string
{
    if ($this->context->controller->php_self !== 'product') {
        return '';
    }

    return '<meta name="acmebadge:enabled" content="1">';
}

Returning an empty string is perfectly fine: it means "I have nothing to add". Avoid heavy work here. The hook runs on every page, so a database query in displayHeader is paid by every visitor.

displayProductAdditionalInfo

This display hook sits in the product page's information area, next to the add-to-cart button. The template passes the current product to it, so your method receives it in $params['product']. The product is the presented product used by the theme, which you can read like an array:

PHP
<?php
// read-only
public function hookDisplayProductAdditionalInfo(array $params): string
{
    $product = $params['product'];

    $this->context->smarty->assign([
        'acmebadge_product_id' => (int) $product['id_product'],
        'acmebadge_label' => $this->l('Free returns within 30 days'),
    ]);

    return $this->fetch('module:acmebadge/views/templates/hook/product-badge.tpl');
}

$this->fetch('module:...') renders a Smarty template that belongs to your module and returns the HTML. Smarty Templates and Theme Integration explains where that file lives and how a theme can replace it. Keep the key names you read from $params to a minimum and check them: the exact keys can differ between hooks and shop versions, so a quick dump($params) in a development shop (see Setting Up a Development Environment) is the honest way to see what you got.

displayShoppingCart

displayShoppingCart appears on the cart page. There is no product here; the data you want is the cart, which you take from the context:

PHP
<?php
// read-only
public function hookDisplayShoppingCart(array $params): string
{
    $cart = $this->context->cart;
    $total = (float) $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS);

    $this->context->smarty->assign('acmebadge_total', $total);

    return $this->fetch('module:acmebadge/views/templates/hook/cart-progress.tpl');
}

Cart::getOrderTotal() takes a "with tax" flag and a "type" constant. The money is in the shop's currency; if you compare with a threshold, think in minor units as explained in Money as Integers.

About hook parameters

Every hook call passes one array. Some points to remember:

  1. The keys depend on the hook. The core code that calls the hook decides what it puts in. There is no type checking, so read defensively with $params['key'] ?? null.
  2. PrestaShop adds common entries (such as the cookie and the cart) to many calls, but do not rely on them; prefer $this->context.
  3. Objects are handles. If a hook gives you an object and you change it, the caller sees the change. Scalars are copies, unless the caller passed them by reference.
  4. Display hooks return strings. Never echo from a hook method; the returned text is what gets placed in the page.

A stand-in storefront

This first stand-in shows the asset flow. A tiny asset manager collects stylesheets and scripts, sorts them by priority and renders them. A module registers its files only on the product page, and another adds a tag in displayHeader. The classes are our own; only the idea (ids, priority, position, php_self) matches PrestaShop.

PHP Stand-in: assets and displayHeader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the output: on the product page both modules add files, and the analytics script (priority 20) comes before the badge script (priority 150). On the cart page the badge module registers nothing, but its displayHeader method still runs, because the stand-in, like a real shop, calls it on every page.

A stand-in product and cart

The second stand-in shows how the two display hooks use their input. The product hook reads the presented product from $params; the cart hook reads the cart from the context. Prices are integer cents to avoid rounding problems.

PHP Stand-in: product and cart hooks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice the escaping: the product name contains a tag, and e() turns it into harmless text. Real templates must do the same (Security in Modules).

Common mistakes

  • Forgetting registerHook and wondering why nothing happens.
  • Echoing instead of returning from a display hook.
  • Loading assets on every page instead of checking php_self.
  • Expecting output from a hook the theme does not call. Check the theme template.
  • Heavy work in displayHeader, which runs on every page.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where should a module register its CSS and JavaScript files in the modern approach?

    Registering through the controller lets PrestaShop order, combine and place the files. Hard-coded tags in a display hook bypass that pipeline.
  2. 2. What must a display hook method do with the HTML it produces?

    Display hooks return a string, and PrestaShop places that string where the hook is called in the template. Echoing can print it in the wrong place.
  3. 3. Your displayProductAdditionalInfo method never runs, although the method exists. What is the most likely cause?

    A hook method runs only if the module is registered on it, and a display hook shows output only if the active theme calls it in a template.
  4. 4. Two stylesheets are registered with priority 50 and 150. Which one loads first?

    Lower numbers load earlier. A priority of 150 puts your file after the theme's, which helps your rules win ties.
  5. 5. Why check $this->context->controller->php_self before registering assets?

    php_self is the current page name. Loading assets only where needed keeps other pages lighter and faster.

Summary

  • Front office hooks are openings in theme templates; display hooks return HTML, action hooks react to events.
  • Register every hook your module uses with registerHook(); the method is named hook plus the capitalized hook name.
  • Register CSS and JavaScript in actionFrontControllerSetMedia with unique ids, paths relative to the shop root, a priority and (for scripts) a position.
  • displayHeader is for head content that is not an asset file; keep it cheap because it runs on every page.
  • displayProductAdditionalInfo receives the presented product; displayShoppingCart works from the context's cart.
  • Read hook parameters defensively, return strings from display hooks, and always escape output.

Next, add extension points of your own: Creating and Dispatching Your Own Hooks.