PHP Hooks

This page is generated from HOOKS.md in the Typography Stylist source. Edit it there — edits made here are kept, but they stop this page from being updated until the conflict is resolved.

PHP Actions

typost_editor_assets

Fired at the end of enqueue_block_editor_assets(). Use this to enqueue your extension’s editor scripts and styles.

add_action('typost_editor_assets', function() {
    wp_enqueue_script(
        'my-extension-editor',
        plugins_url('assets/js/editor.js', __FILE__),
        array('typost-block-editor', 'wp-element', 'wp-components'),
        '1.0.0',
        true
    );
});

Important: Use typost-block-editor as a script dependency to ensure your script loads after Typography Stylist’s editor scripts and window.typostHooks is available.

Adobe Fonts kits in the block editor (since 2.3.1). The editor no longer loads every Adobe Fonts kit stylesheet. PHP enqueues the kits that the edited post’s saved content uses, plus “Load on all pages” fonts and typost_force_enqueue_font_ids fonts. window.typostFontKits (script handle typost-editor-font-kits, a dependency of typost-block-editor) adds any other kit to the editor page and to the canvas iframe:

  • Fonts in blocks load automatically, also inside synced patterns and template parts. The loader watches the block editor store. It reads a block’s top-level fontId and paragraphStyleId attributes. It also finds the text data-font-id="N", var(--font-N), data-style-id="…" and typost-ps-* in string and rich-text attributes, and in object and array attributes (read as JSON). A font ID kept in any other form (for example {"layer": {"font": 12}}) is not found: ask for its kit yourself.
  • Text that your extension shows in a font that is not yet in a block (a preview, a picker, a panel) must ask for the kit: window.typostFontKits.ensureFontId(fontId) or ensureFontIds([ids]). Both follow font replacements. Guard the call with if (window.typostFontKits).
  • On the settings page, use window.typostAdminFonts instead (see typost_admin_assets). The editor also defines window.typostAdminFonts.ensureFontId, so code that runs in both places can call that name.

typost_admin_assets

Fired at the end of enqueue_admin_assets(). Use this to enqueue scripts and styles for the Typography Stylist settings page.

add_action('typost_admin_assets', function() {
    wp_enqueue_script('my-extension-admin', plugins_url('assets/js/admin.js', __FILE__), array('jquery'), '1.0.0', true);
    wp_enqueue_style('my-extension-admin', plugins_url('assets/css/admin.css', __FILE__), array(), '1.0.0');
});

Since 2.3.1 the action fires once per page load, from admin_enqueue_scripts. Before 2.3.1 it fired twice (from admin_print_styles-{hook} and admin_print_scripts-{hook}), so data passed to wp_localize_script() here printed twice.

Fonts on the settings page (since 2.3.1). The settings page no longer enqueues Adobe Fonts kit stylesheets up front, and font card headings past the first screen get their font only when they scroll into view. An extension that shows text in a plugin font on this page opts in with attributes on the element:

  • data-typost-font-id="N" — core loads the Adobe Fonts kit stylesheet for font N when the element comes into view. Uploaded fonts and adopted Font Library fonts need nothing: their @font-face rules are already on the page. Custom font definitions (manual fonts) are not loaded on this page — the theme or another plugin loads them on the site — so text in one shows a fallback font here.
  • data-typost-font-family="…" — core sets this CSS font-family on the element when it comes into view.

Core scans the page once on DOM ready and again after each font list refresh. For markup you add later, or when you change the attribute, call window.typostAdminFonts.scan(element) (checks the element and its descendants) or window.typostAdminFonts.watch(element). To load a kit directly, call window.typostAdminFonts.ensureFontId(fontId); the bundled Glyphs panel does this when a font is selected. Guard the calls with if (window.typostAdminFonts) — the object exists only on the settings page, and it is defined only after typost-admin loads, so depend on that handle.

typost_register_rest_routes

Fired at the end of register_rest_routes(). Register your extension’s REST API endpoints under the typost/v1 namespace.

Write requests (POST, PUT, PATCH, DELETE) to any typost/v1 route share one limit: 50 per minute for each user (since 2.3.2). The count starts after your permission callback passes, and an extra request gets a 429 rate_limit_exceeded error. Read requests are not counted. A route in another namespace can use Typost::get_instance()->check_permissions() as its permission callback to get the same limit.

add_action('typost_register_rest_routes', function() {
    register_rest_route('typost/v1', '/my-extension/data', array(
        'methods'             => WP_REST_Server::READABLE,
        'callback'            => 'my_extension_get_data',
        'permission_callback' => function() {
            return current_user_can('edit_posts');
        },
    ));
});

typost_cache_clear

Fired when Typography Stylist clears its caches (manual clear from admin or automatic invalidation). Clear your extension’s caches here.

add_action('typost_cache_clear', function() {
    delete_transient('my_extension_cache');
});

typost_font_uploaded

Fired after a font kit is successfully uploaded and processed. Receives an array of font entry objects that were added (a single ZIP kit may contain multiple font files).

add_action('typost_font_uploaded', function($font_entries) {
    // Example: Parse variable font axes on upload
    foreach ($font_entries as $entry) {
        $axes = parse_font_axes($entry['file_path']);
        if ($axes) {
            update_option('my_extension_axes_' . $entry['id'], $axes);
        }
    }
}, 10, 1);

Parameters:

  • $font_entries (array) — Array of font entry objects that were added from the kit

typost_font_deleted

Fired after a font is successfully deleted. Receives the font ID and the deleted font’s data.

add_action('typost_font_deleted', function($id, $font_data) {
    delete_option('my_extension_axes_' . $id);
}, 10, 2);

Parameters:

  • $id (string) — The deleted font’s ID
  • $font_data (array) — The deleted font’s data array

typost_after_weight_checkboxes

Fired after the weight checkboxes in font edit forms on the admin page. Use this to inject additional per-font controls (e.g., variable font axis configuration).

add_action('typost_after_weight_checkboxes', function($font, $prefix) {
    // $font  — Font data array
    // $prefix — Form prefix string ('font', 'adobe', or 'manual')
    echo '<div class="my-extension-font-options">';
    echo '<label><input type="checkbox" /> Enable Variable Font</label>';
    echo '</div>';
}, 10, 2);

Parameters:

  • $font (array) — The font data array for the current font being edited
  • $prefix (string) — Form field prefix: 'font' (uploaded), 'adobe', or 'manual'

typost_font_saved

Fired after a font’s settings are saved via PATCH endpoints (fallback updates, weight changes, etc.). Use this to save extension-specific per-font data.

add_action('typost_font_saved', function($id, $font_data, $type) {
    // Save extension data for this font
    update_option('my_extension_font_' . $id, $my_data);
}, 10, 3);

Parameters:

  • $id (string) — The font’s string ID (e.g., 'kit-123-inter')
  • $font_data (array) — The updated font data array
  • $type (string) — Font type: 'uploaded', 'adobe', or 'manual'

typost_admin_tab_content_{tab_id}

Fired to render the content of an extension-registered admin tab. The {tab_id} is the id value from your tab registration.

add_action('typost_admin_tab_content_my-tab', function($instance) {
    echo '<h2>My Extension Settings</h2>';
    echo '<p>Configure your extension here.</p>';
});

typost_admin_tab_after_{tab_id}

Fired at the end of each built-in tab panel. Use this to append content to existing tabs.

Available tab IDs: presets, fonts, options, accessibility, replacements, help

add_action('typost_admin_tab_after_fonts', function($instance) {
    echo '<div class="my-extension-font-info">';
    echo '<h3>Variable Font Axes</h3>';
    // Additional font information
    echo '</div>';
});

typost_admin_options_rows

Since 2.3.0. Fired inside the Options tab settings table, after the core rows. Use it for a single editor-behaviour setting that would not justify a tab of its own — every such option then lives in one place.

Echo complete <tr> rows. Mark checkbox inputs with data-typost-option="1" so the tab’s AJAX save collects them, and register the option key with typost_admin_options_checkboxes so it is actually persisted.

add_action('typost_admin_options_rows', function($instance) {
    ?>
    <tr>
        <th scope="row"><?php esc_html_e('My Toolbar Button', 'my-extension'); ?></th>
        <td>
            <input type="checkbox" id="my_ext_toolbar" name="my_ext_toolbar"
                   value="1" data-typost-option="1"
                   <?php checked(get_option('my_ext_toolbar', false)); ?> />
            <label for="my_ext_toolbar"><?php esc_html_e('Show the button', 'my-extension'); ?></label>
        </td>
    </tr>
    <?php
});

Expose the value to the editor through typost_editor_data. That filter runs after the localized-data transient is read, so a toggle takes effect immediately rather than when the hour-long cache expires.

PHP Filters

typost_editor_data

Filter the data passed to the block editor via wp_localize_script(). Add your extension’s data to typostData.

add_filter('typost_editor_data', function($data) {
    $data['myExtensionSettings'] = get_option('my_extension_settings', array());
    return $data;
});

Note: This data is cached in a transient. The nonce is always injected fresh (not cached).

wp_localize_script() casts scalars to strings, so booleans arrive as "1" / "" — truthy and falsy as expected, but never true/false. Fields worth knowing about:

  • blockEnterLineBreak (since 2.3.0) — "1" when Enter inside a Typography Stylist block inserts a line break (the default), "" when Enter starts a new block. The editor itself does not read this: the behaviour is driven by core’s splitting block support, added server-side in filter_block_splitting_support(), so wp.blocks.hasBlockSupport('typost/block', 'splitting', false) is the authoritative check inside the editor. The localized value is here for extensions that need the user’s setting without reaching into the block registry.
  • newFontSizeUnit (since 2.3.2) — "rem" (the default) or "px" when Settings → Typography Stylist → Options → “Write new font sizes in px” is on (#248). The unit new content writes its font sizes in. An extension that creates a typost/block in code should pass fontSizeUnit with this value: block.json’s rem default also decides how saved blocks parse, so it cannot follow the setting. An extension that writes a new inline font size should write it in this unit. getNewFontSizeUnit() in assets/js/font-size-units.js reads it.

typost_admin_localize_data

Filter the data passed to the admin page via wp_localize_script().

add_filter('typost_admin_localize_data', function($data) {
    $data['myExtensionData'] = get_option('my_extension_data', array());
    return $data;
});

typost_admin_tabs

Filter the array of admin settings tabs. Add your own tabs or modify existing ones.

add_filter('typost_admin_tabs', function($tabs) {
    $tabs[] = array(
        'id'       => 'my-tab',
        'label'    => __('My Extension', 'my-text-domain'),
        'priority' => 25, // Between Font Features (20) and Options (30)
    );
    return $tabs;
});

Tab properties:

  • id (string) — Unique tab identifier, used in data-tab attribute and action hooks
  • label (string) — Display text for the tab button
  • priority (int) — Sort order (lower = further left). Built-in tabs: Fonts=10, Features=20, Options=30, Accessibility=40, Replacements=50, Help=100

typost_font_card_badges

Filter the extension badge HTML rendered in each font card header on the Custom Fonts tab. Extension badges render before the source pills (Uploaded, Adobe Fonts, WP Library, …) so state badges like the Variable Fonts module’s “Variable” pill lead the row. Return accumulated HTML — always append to (never replace) the incoming value, since multiple extensions may add badges. Output is passed through wp_kses_post().

add_filter('typost_font_card_badges', function($badges, $font, $type) {
    // $type is 'uploaded', 'adobe', 'manual', or 'wplibrary'
    // $font is the entry being rendered (wplibrary entries have slug, not id)
    if (my_extension_applies_to($font)) {
        $badges .= '<span class="typost-font-type-badge my-badge">' .
            esc_html__('My Badge', 'my-text-domain') . '</span>';
    }
    return $badges;
}, 10, 3);

The bundled Variable Fonts module uses this to show a “Variable” pill (with the configured axis tags in its tooltip) on variable fonts.

typost_admin_options_checkboxes

Since 2.3.0. Register option keys for checkboxes you rendered on typost_admin_options_rows, so that both the Options tab’s AJAX save and its no-JavaScript POST fallback persist them. Values are stored as '1' / '0'.

add_filter('typost_admin_options_checkboxes', function($options) {
    $options[] = 'typost_my_extension_toolbar';
    return $options;
});

Keys must be prefixed typost_; anything else is ignored. This is deliberate — an extension may add its own settings to the form, not use it to write arbitrary WordPress options.

These options are also exported with the Options section of an export file (since 2.3.5). Give each one a label and a default with typost_export_option_details.

typost_export_option_details

Since 2.3.5. The label and default of each checkbox registered with typost_admin_options_checkboxes, for the Options section of an export file (#205). The import preview shows the label next to the value on this site and the value in the file. The default is the value when the option was never saved. Without an entry, the preview shows the option name and treats an unsaved option as off.

add_filter('typost_export_option_details', function($details) {
    $details['typost_my_extension_toolbar'] = array(
        'label'   => __('Add a My Extension button to the block toolbar', 'my-extension'),
        'default' => true,
    );
    return $details;
});

typost_available_features

Filter the list of available OpenType features.

add_filter('typost_available_features', function($features) {
    // Add a custom feature
    $features[] = array(
        'id'          => 'cv01',
        'name'        => 'Character Variant 1',
        'category'    => 'alternates',
        'description' => 'First character variant set',
    );
    return $features;
});

typost_presets

Filter the presets list (saved and default presets combined).

add_filter('typost_presets', function($presets) {
    $presets[] = array(
        'id'       => 'my-preset',
        'name'     => 'Custom Preset',
        'features' => array('liga', 'dlig', 'ss01'),
        // Optional. A font-family stack; the inline format resolves it to the
        // matching plugin font and writes var(--font-N). Since 2.3.2.
        'fontFamily' => 'Fraunces',
    );
    return $presets;
});

A preset without fontFamily keeps the font of the selected text.

typost_force_enqueue_font_ids

Since 2.1.0. Force specific fonts (by numeric font ID) to load on every frontend page, even when the post-content scan finds no styled content. Use this when your theme or extension references a font’s --font-N CSS variable from its own stylesheets — the content scan can’t see those references, so without this filter neither the variable definitions nor the @font-face rules would be output.

add_filter('typost_force_enqueue_font_ids', function($ids) {
    // e.g. fonts assigned to theme color schemes
    $ids[] = 12;
    $ids[] = 27;
    return $ids;
});

Details:

  • Return an array of positive integer font IDs; invalid entries are discarded.
  • Forced IDs are resolved through the font-replacement chain, so referencing a deleted font’s ID loads its replacement (and keeps the alias variable).
  • Forcing any ID causes the --font-N variables <style> block and the frontend stylesheet handle to be output on all pages.
  • The result is memoized per request and feeds transient cache keys — callbacks must return stable output for a given request.

typost_content_font_ids

Since 2.3.0. Report font IDs that a piece of content uses indirectly. The frontend font scan recognizes data-font, data-font-id and --font-N. Content styled only through a class — a <span data-style-id="N"> or a block with typost-ps-N — names no font, so the scan cannot see it. Return the numeric font IDs those references stand for and core enqueues their @font-face and --font-N variables for that page only. The bundled Paragraph Styles module uses this filter.

add_filter('typost_content_font_ids', function($ids, $content) {
    if (preg_match_all('/data-my-preset=["\'\\\\]*(\d+)/', $content, $m)) {
        foreach ($m[1] as $preset_id) {
            $ids[] = my_plugin_font_id_for_preset((int) $preset_id);
        }
    }
    return $ids;
}, 10, 2);

Details:

  • $content is the raw post content plus its rendered form for the page scan, and a block’s content attribute for the block scan — attribute JSON escapes quotes, so match ["\'\\\\]* around values.
  • Return an array of positive integer font IDs; invalid entries are discarded. IDs resolve through the font-replacement chain like every other detected font.
  • Results are cached per post for 12 hours with the rest of the detection. When the data behind your IDs changes, call Typost::get_instance()->clear_font_detection_cache(). Call it on saves, not on every request: under a persistent object cache (Redis, Memcached) it flushes the whole object cache, because the wildcard transient deletes cannot reach the cached copies.
  • Unlike typost_force_enqueue_font_ids, this loads fonts only on pages whose content references them.

typost_export_sections

Since 2.3.5. Add a section to the export file that Settings → Typography Stylist → Export & Import writes and reads (#205). Core registers presets, options and featureVisibility with this filter, the bundled Paragraph Styles module paragraphStyles, and the bundled Variable Fonts module variableFonts. See Export Sections for the section definition and the rules a section must follow.

add_filter('typost_export_sections', function($sections) {
    $sections[] = array(
        'id'         => 'myExtension',
        'label'      => __('My extension settings', 'my-extension'),
        'capability' => 'manage_options',
        'options'    => array('typost_my_extension_settings'),
        'export'     => 'my_extension_export',
        'preview'    => 'my_extension_preview',
        'import'     => 'my_extension_import',
    );
    return $sections;
});

typost_font_axis_tags

Since 2.3.5. The variable font axis tags defined for a font, by numeric font ID. Import uses it to warn when an imported paragraph style sets an axis that the font on the receiving site does not define. The bundled Variable Fonts module answers from its axis definitions (an empty array for a font with none). null, the default, means “unknown”, and import then gives no axis warning.

add_filter('typost_font_axis_tags', function($tags, $font_id) {
    if (42 === $font_id) {
        return array('wght', 'opsz');
    }
    return $tags;
}, 10, 2);

typost_force_enqueue_paragraph_style_ids

Since 2.3.1. Print the CSS rules of specific paragraph styles on every frontend page. A single post or page prints the rules only for the styles that it uses. A page that lists posts (an archive, the blog page, search results) prints every style. Use this filter when your theme or extension puts a typost-ps-N class or a data-style-id attribute in markup that the plugin does not scan.

add_filter('typost_force_enqueue_paragraph_style_ids', function($ids) {
    // e.g. a theme template that puts typost-ps-3 on the site title
    $ids[] = 3;
    return $ids;
});

Details:

  • Return an array of style IDs. Integers and legacy ps_… IDs are accepted. Other entries are discarded.
  • The fonts of these styles load on every page too, through typost_force_enqueue_font_ids.
  • The result is memoized per request. Callbacks must return stable output for a given request.
  • You do not need this filter for blocks. The plugin scans the queried post, the synced patterns in it, and, on a classic theme, the block widgets. It also records the styles of every block as it renders. A block theme renders its template parts before wp_head, so their styles print in the head. A block that renders after wp_head (for example a block in a custom query loop) gets its rules in a second <style> element at the end of wp_footer. Markup that is not a block, such as a classic text widget or a template file, needs this filter.
  • Content loaded by AJAX does not run wp_head or wp_footer, so it can use only the rules that the page that loads it printed. A “load more” button on an archive is safe, because archives print every style. If a single post or page loads content by AJAX (for example related posts), add the style IDs of that content with this filter. The core Query Loop block’s own pagination is not affected: it copies the <style> elements of the page it loads.