跳转到主要内容

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">

%s

$%0.2f

',\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"; }

Canvas Tote

$24.00

Coffee & Code Mug

$16.50

Here is the complete embed: ``` ``` 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 echo 'Hello from PHP ' . phpversion(); Hello from PHP 8.4.x ``` ``` 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 ` ``` A literal `` 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: ``` ``` 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 ``. `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 echo 20 + 22; ``` ## 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 ``` ``` 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 ``` ``` ### 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 ` ``` 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 ``` ``` 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. ``` ``` `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 ``` ``` For one-line output, use the `expected-output` attribute: <?php echo 'Ready'; ``` ``` ## 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 ``` ``` The selector form is useful when generated markup cannot guarantee simple ids: <?php require '/wordpress/wp-load.php'; echo docs\_greet( 'Grace' ); Hello, Grace ``` ``` Prefer ` ``` <?php require '/wordpress/wp-load.php'; echo get\_bloginfo( 'version' ); 6.8 ``` ``` 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' ); ``` ``` ## 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. ``` ``` ## 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: ``` ``` 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 | `` | | A tutorial step where readers should edit code inline | `` | | Shared setup across examples | `` | | Hidden PHP setup before every run | `` | | PHP source without an opening tag | `` | | A pure PHP language example | `` | | A runnable example that should not be edited | `` | | 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.