After PHP transform

Registering a plugin after usePHP() lets you modify the final HTML after Vite's transforms and after PHP fragments have been restored.

When to use this

  • Inject analytics, tracking or metadata into the final HTML.
  • Post-process the output generated by PHP.
  • Apply transforms that should not interfere with PHP execution.

Example: inject analytics

// vite.config.ts
import { defineConfig } from 'vite';
import usePHP from 'vite-plugin-php';

export default defineConfig({
    plugins: [
        usePHP(),
        {
            name: 'inject-analytics',
            transformIndexHtml: {
                order: 'post',
                handler(html, ctx) {
                    return html.replace(
                        '</head>',
                        `<script async src="https://analytics.example.com/script.js"></script>\n</head>`,
                    );
                },
            },
        },
    ],
});

Because this plugin runs after usePHP() with order: 'post', the PHP has already been executed and restored. Any HTML you inject here is sent to the browser as-is.

Example: add a timestamp comment

{
    name: 'build-timestamp',
    transformIndexHtml: {
        order: 'post',
        handler(html, ctx) {
            return html.replace(
                '</body>',
                `<!-- Generated at ${new Date().toISOString()} -->\n</body>`,
            );
        },
    },
}

Shorthand syntax

You can also use the shorthand form without order: 'post':

(usePHP(),
    {
        name: 'post-transform',
        transformIndexHtml(html, ctx) {
            return html.replace(
                '</body>',
                '<div>Injected after PHP</div>\n</body>',
            );
        },
    });

In this case the plugin order depends on Vite's internal ordering, but because it is placed after usePHP() it typically runs after the plugin's post hook.