# PHP code snippets and embeds

Use `<php-snippet>` when you want readers to run PHP or WordPress code directly  
from a docs page, tutorial, blog post, or demo. It renders a syntax-highlighted  
code block with a Run button and starts a real Playground runtime only when the  
reader asks for it.

The runtime is shared across matching snippets on the same page, so a tutorial  
can include several runnable examples without starting WordPress over and over.

## Try it

The example below is editable and runnable. It also uses a Blueprint to install  
a small mu-plugin before the snippet runs, so the PHP code can call a helper  
function that did not exist in the default WordPress install.

{
"steps": [
{
"step": "writeFile",
"path": "/wordpress/wp-content/mu-plugins/product-cards.php",
"data": "<?php\nfunction docs\_render\_product\_card( array $product ): string {\n\treturn sprintf(\n\t\t'<article class=\"product-card\"><h3>%s</h3><p>$%0.2f</p></article>',\n\t\tesc\_html( $product['name'] ),\n\t\t$product['price']\n\t);\n}\n"
}
]
}

<?php
require '/wordpress/wp-load.php';
$products = [
[
'name' => 'Canvas Tote',
'price' => 24,
],
[
'name' => 'Coffee & Code Mug',
'price' => 16.5,
],
];
foreach ( $products as $product ) {
echo docs\_render\_product\_card( $product ) . "\n";
}

<article class="product-card"><h3>Canvas Tote</h3><p>$24.00</p></article>
<article class="product-card"><h3>Coffee &amp; Code Mug</h3><p>$16.50</p></article>

Here is the complete embed:

```
<script type="module" src="https://playground.wordpress.net/php-code-snippet.js"></script>

<script id="product-card-blueprint" type="application/json">
    {
        "steps": [
            {
                "step": "writeFile",
                "path": "/wordpress/wp-content/mu-plugins/product-cards.php",
                "data": "<?php\nfunction docs_render_product_card( array $product ): string {\n\treturn sprintf(\n\t\t'<article class=\"product-card\"><h3>%s</h3><p>$%0.2f</p></article>',\n\t\tesc_html( $product['name'] ),\n\t\t$product['price']\n\t);\n}\n"
            }
        ]
    }
</script>

<php-snippet name="product-card.php" blueprint="product-card-blueprint">
    <script type="application/x-php">
        <?php
        require '/wordpress/wp-load.php';

        $products = [
            [
                'name'  => 'Canvas Tote',
                'price' => 24,
            ],
            [
                'name'  => 'Coffee & Code Mug',
                'price' => 16.5,
            ],
        ];

        foreach ( $products as $product ) {
            echo docs_render_product_card( $product ) . "\n";
        }
    </script>
    <script type="text/expected-output">
        <article class="product-card"><h3>Canvas Tote</h3><p>$24.00</p></article>
        <article class="product-card"><h3>Coffee &amp; Code Mug</h3><p>$16.50</p></article>
    </script>
</php-snippet>
```

Use this pattern when each example should start from the same prepared site:  
helper functions, mu-plugins, options, themes, demo files, or sample content.

## Start with one snippet

For a basic runnable example, add the component script once and place PHP inside  
`<php-snippet>`:

<?php
echo 'Hello from PHP ' . phpversion();

Hello from PHP 8.4.x

```
<script type="module" src="https://playground.wordpress.net/php-code-snippet.js"></script>

<php-snippet name="hello.php">
    <script type="application/x-php">
        <?php
        echo 'Hello from PHP ' . phpversion();
    </script>
    <script type="text/expected-output">
        Hello from PHP 8.4.x
    </script>
</php-snippet>
```

The script itself is small. PHP, WordPress, and the WASM runtime are fetched  
later, after the first Run click. The expected output appears before Run and is  
replaced with the exact PHP version after execution.

## Write PHP safely in HTML

Put inline PHP in a `<script type="application/x-php">` child. Browsers ignore  
script tags with unknown types, which means PHP strings can contain HTML without  
escaping every `<` character.

<?php
require '/wordpress/wp-load.php';
$html = '<img decoding="async" src="hero.jpg" alt="Hero">';
$tags = new WP\_HTML\_Tag\_Processor( $html );
if ( $tags->next\_tag( 'img' ) ) {
$tags->set\_attribute( 'loading', 'lazy' );
}
echo $tags->get\_updated\_html();

<img decoding="async" src="hero.jpg" alt="Hero" loading="lazy">

```
<php-snippet name="html-api.php">
    <script type="application/x-php">
        <?php
        require '/wordpress/wp-load.php';

        $html = '<img src="hero.jpg" alt="Hero">';
        $tags = new WP_HTML_Tag_Processor( $html );

        if ( $tags->next_tag( 'img' ) ) {
            $tags->set_attribute( 'loading', 'lazy' );
        }

        echo $tags->get_updated_html();
    </script>
    <script type="text/expected-output">
        <img src="hero.jpg" alt="Hero" loading="lazy">
    </script>
</php-snippet>
```

A literal `</script>` still closes the child script element, even when it is  
inside a PHP string. Use JSON-encoded child payloads when the PHP source or  
expected output contains that sequence:

```
<php-snippet name="example.php">
    <script type="application/x-php+json">
        "\u003C?php\necho '\u003C/script\u003E';"
    </script>
    <script type="text/expected-output+json">
        "\u003C/script\u003E"
    </script>
</php-snippet>
```

Both payloads are parsed as JSON and must decode to strings; other JSON values  
are rejected. Encode `<` as `\u003C` so the HTML parser never sees a literal  
`</script>`. `JSON.stringify()` does not escape `<` by itself. The unencoded  
`application/x-php` and `text/expected-output` types remain supported.

Very short snippets can also be written as text, as long as PHP opening tags are  
escaped:

<?php echo 20 + 22;

```
<php-snippet name="sum.php" expected-output="42"> &lt;?php echo 20 + 22; </php-snippet>
```

## Use WordPress APIs

Snippets run in a real WordPress installation by default. Load WordPress with  
`require '/wordpress/wp-load.php'`, then call core APIs as usual.

<?php
require '/wordpress/wp-load.php';
update\_option( 'blogname', 'Snippet Docs' );
echo get\_bloginfo( 'name' );

Snippet Docs

```
<php-snippet name="site-title.php">
    <script type="application/x-php">
        <?php
        require '/wordpress/wp-load.php';

        update_option( 'blogname', 'Snippet Docs' );
        echo get_bloginfo( 'name' );
    </script>
    <script type="text/expected-output">
        Snippet Docs
    </script>
</php-snippet>
```

If your example is pure PHP and does not need WordPress, use `wp="none"` to skip  
the WordPress download and boot step:

<?php
echo 'WordPress installed: ';
echo file\_exists( '/wordpress/wp-load.php' ) ? 'yes' : 'no';

WordPress installed: no

```
<php-snippet name="pure-php.php" wp="none">
    <script type="application/x-php">
        <?php
        echo 'WordPress installed: ';
        echo file_exists( '/wordpress/wp-load.php' ) ? 'yes' : 'no';
    </script>
    <script type="text/expected-output">
        WordPress installed: no
    </script>
</php-snippet>
```

### Automatically prepend a hidden PHP script

`auto-prepend-script` mirrors PHP’s  
[`auto_prepend_file`](https://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file)  
`php.ini` directive: the referenced PHP script runs before the snippet’s main  
file on every request. Unlike the PHP directive, the attribute takes the id or  
CSS selector of an inert PHP `<script>` element. Use it when setup code should  
not appear in the editable example:

```
<script id="load-wordpress" type="application/x-php">
    <?php
    require_once '/wordpress/wp-load.php';
</script>

<php-snippet name="site-title.php" auto-prepend-script="#load-wordpress" implicit-php-open-tag>
    <script type="application/x-php">
        echo get_bloginfo( 'name' );
    </script>
</php-snippet>
```

The referenced script must start with `<?php`. It remains outside the visible  
editor and runs before every click, including after the reader edits the  
snippet. Snippets with different auto-prepended scripts can still share one  
runtime.

`implicit-php-open-tag` adds the PHP opening tag omitted from the visible  
source. Playground adds it on the first line of the execution file, so PHP  
errors still point to the displayed line. Diagnostics use a filesystem-safe  
form of the `name` attribute as the filename. Code starting with any PHP  
opening tag (`<?php`, `<?=`, or `<?`) is rejected; remove  
`implicit-php-open-tag` when the source is already a complete PHP file.

Without `implicit-php-open-tag`, snippets using `auto-prepend-script` must  
include their own PHP opening tag. The two attributes are independent, so an  
implicit opening tag also works without an auto-prepended script.

## Edit examples in place

Runnable snippets are editable by default. The edited code is kept only in the  
current page session; refreshing restores the original snippet.

<?php
$numbers = range( 1, 5 );
echo array\_sum( $numbers );

15

```
<php-snippet name="scratch.php">
    <script type="application/x-php">
        <?php
        $numbers = range( 1, 5 );
        echo array_sum( $numbers );
    </script>
    <script type="text/expected-output">
        15
    </script>
</php-snippet>
```

Editable snippets also run with `Ctrl+Enter` or `Cmd+Enter` while the editor is  
focused.

Use `readonly` for runnable examples that should be copied or run as-is:

<?php
echo 'This example can run, but the code is locked.';

This example can run, but the code is locked.

```
<php-snippet name="reference.php" readonly>
    <script type="application/x-php">
        <?php
        echo 'This example can run, but the code is locked.';
    </script>
    <script type="text/expected-output">
        This example can run, but the code is locked.
    </script>
</php-snippet>
```

`editable="false"` works as a compatibility alias for `readonly`.

## Show output before Run

Use expected output when you want the result visible immediately. The placeholder  
is replaced with real runtime output after the reader clicks Run.

<?php
echo '2 + 2 = ' . ( 2 + 2 );

2 + 2 = 4

```
<php-snippet name="precomputed.php">
    <script type="application/x-php">
        <?php
        echo '2 + 2 = ' . ( 2 + 2 );
    </script>
    <script type="text/expected-output">
        2 + 2 = 4
    </script>
</php-snippet>
```

For one-line output, use the `expected-output` attribute:

<?php
echo 'Ready';

```
<php-snippet name="one-line.php" expected-output="Ready">
    <script type="application/x-php">
        <?php
        echo 'Ready';
    </script>
</php-snippet>
```

## Prepare a site with a Blueprint

Use `blueprint` when snippets need setup before the PHP code runs. Put a JSON  
[Blueprint](https://developer.wordpress.org/playground/blueprints/) in the page and point snippets at it by id or CSS  
selector.

{
"steps": [
{
"step": "writeFile",
"path": "/wordpress/wp-content/mu-plugins/helpers.php",
"data": "<?php\nfunction docs\_greet( $name ) {\n\treturn 'Hello, ' . $name;\n}\n"
}
]
}

<?php
require '/wordpress/wp-load.php';
echo docs\_greet( 'Ada' );

Hello, Ada

```
<script id="setup-blueprint" type="application/json">
    {
        "steps": [
            {
                "step": "writeFile",
                "path": "/wordpress/wp-content/mu-plugins/helpers.php",
                "data": "<?php\nfunction docs_greet( $name ) {\n\treturn 'Hello, ' . $name;\n}\n"
            }
        ]
    }
</script>

<php-snippet name="greeting.php" blueprint="setup-blueprint">
    <script type="application/x-php">
        <?php
        require '/wordpress/wp-load.php';
        echo docs_greet( 'Ada' );
    </script>
    <script type="text/expected-output">
        Hello, Ada
    </script>
</php-snippet>
```

The selector form is useful when generated markup cannot guarantee simple ids:

<?php
require '/wordpress/wp-load.php';
echo docs\_greet( 'Grace' );

Hello, Grace

```
<php-snippet blueprint="#setup-blueprint" name="with-selector.php">
    <script type="application/x-php">
        <?php
        require '/wordpress/wp-load.php';
        echo docs_greet( 'Grace' );
    </script>
    <script type="text/expected-output">
        Hello, Grace
    </script>
</php-snippet>
```

Prefer `<script type="application/json">` for Blueprints. Its contents are raw  
text, so embedded PHP strings such as `<?php` are safe. A `<template>` can work,  
but its contents are parsed as HTML; if you use one, escape `<` in embedded PHP  
strings as `\u003c`.

## Load PHP from another file

Use `src` when the PHP source should live in a separate file:

```
<php-snippet name="external-example.php" src="/snippets/external-example.php" expected-output="Loaded from an external file"></php-snippet>
```

The URL resolves from the page that contains the snippet. If the file is hosted  
on another origin, serve it with an `Access-Control-Allow-Origin` header that  
allows the documentation page.

`src` loads only the snippet body. Use a Blueprint when you need support files,  
plugins, options, or other setup before the snippet runs. The `expected-output`  
attribute is still useful with `src` when you already know what the external PHP  
file prints.

## Pin PHP or WordPress versions

The default PHP version is `8.4`, and the default WordPress version is `latest`.  
Set `php` or `wp` when the example depends on a specific version.

<?php
enum Status {
case Draft;
case Published;
}
echo Status::Published->name;

Published

```
<php-snippet name="enum.php" php="8.4">
    <script type="application/x-php">
        <?php
        enum Status {
            case Draft;
            case Published;
        }

        echo Status::Published->name;
    </script>
    <script type="text/expected-output">
        Published
    </script>
</php-snippet>
```

<?php
require '/wordpress/wp-load.php';
echo get\_bloginfo( 'version' );

6.8

```
<php-snippet name="wp-version.php" wp="6.8">
    <script type="application/x-php">
        <?php
        require '/wordpress/wp-load.php';
        echo get_bloginfo( 'version' );
    </script>
    <script type="text/expected-output">
        6.8
    </script>
</php-snippet>
```

See the [Query API reference](https://developer.wordpress.org/playground/developers/apis/query-api/#available-options)  
for available PHP and WordPress versions.

## Show code without running it

Set `runnable="false"` for fragments that should be highlighted but not  
executed, such as incomplete examples or code that depends on external services.

<?php
// This fragment is shown for discussion, not execution.
add\_filter( 'the\_content', 'docs\_filter\_content' );

```
<php-snippet name="illustration.php" runnable="false">
    <script type="application/x-php">
        <?php
        // This fragment is shown for discussion, not execution.
        add_filter( 'the_content', 'docs_filter_content' );
    </script>
</php-snippet>
```

## Self-host the runtime

Most pages should use the hosted runtime from `` https://playground.wordpress.net`.  
Set ``playground-origin` when developing Playground itself, testing a self-hosted  
deployment, or pinning examples to infrastructure you control.

```
<php-snippet name="local-runtime.php" playground-origin="http://localhost:5400">
    <script type="application/x-php">
        <?php
        echo phpversion();
    </script>
    <script type="text/expected-output">
        8.4.x
    </script>
</php-snippet>
```

## Runtime sharing

The first Run click on a page:

1. Loads the Playground client.
2. Creates a hidden iframe pointed at `remote.html`.
3. Boots PHP, and WordPress unless the snippet uses `wp="none"`.
4. Runs the snippet code and writes stdout into the output panel.

Later runs reuse an existing runtime when `playground-origin`, `php`, `wp`, and  
the resolved Blueprint JSON all match. This keeps related snippets fast while  
still isolating examples that need different setup.

## Security and CSP

Snippet PHP runs inside the Playground runtime iframe, not in the parent page.  
The parent page still loads the web component script and creates the hidden  
runtime iframe.

If your site has a Content Security Policy, allow:

- The module script from `https://playground.wordpress.net`.
- The hidden iframe from the same origin.
- Network requests for the PHP, WordPress, and Playground runtime assets.

For stricter environments, self-host the snippet script and use  
`playground-origin` to point snippets at your deployment.

## Standalone PHP Playground

Use the standalone PHP Playground when you want a full-page editor, a shareable  
URL, or an iframe instead of inline examples:

> [playground.wordpress.net/php-playground.html](https://playground.wordpress.net/php-playground.html)

You can embed it directly:

```
<iframe src="https://playground.wordpress.net/php-playground.html#eyJjb2RlIjoiPD9waHBcblxuZWNobyBcIkkgYW0gYSBjb2RlIHNuaXBwZXQhXCI7XG4iLCJwaHAiOiI4LjQifQ==" width="100%" height="600"></iframe>
```

The URL fragment is a base64-encoded JSON payload with `code`, `php`, and `wp`  
fields.

## Which embed should you use?

| Use case | Use |
| --- | --- |
| Several runnable examples in one article | `<php-snippet>` |
| A tutorial step where readers should edit code inline | `<php-snippet>` |
| Shared setup across examples | `<php-snippet blueprint="...">` |
| Hidden PHP setup before every run | `<php-snippet auto-prepend-script="...">` |
| PHP source without an opening tag | `<php-snippet implicit-php-open-tag>` |
| A pure PHP language example | `<php-snippet wp="none">` |
| A runnable example that should not be edited | `<php-snippet readonly>` |
| A single full-page editor with a shareable URL | Standalone PHP Playground |
| A complete WordPress site preview | Standard Playground iframe |

## Troubleshooting

If the snippet does not render, check that the module script loaded and that the  
browser supports custom elements.

If Run never finishes, open DevTools and check failed requests for `remote.html`,  
PHP `.wasm` files, WordPress zip files, Blueprint resources, or cross-origin  
`src` files.

If a Blueprint-backed snippet cannot find helper functions, confirm the  
`blueprint` attribute points to the right element and that the JSON is valid.

If output differs from the expected placeholder, trust the runtime output. The  
placeholder is static documentation; Run executes the current code against the  
selected PHP, WordPress, and Blueprint setup.