Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 68 ยท Block Themes and the Site Editor

PHP in Block Themes

See when a WordPress block theme still needs PHP: functions.php, register_block_style, wp_enqueue_block_style and the render_block filter, with a stand-in.

A block theme moves most of its work into JSON and HTML: theme.json for design, template files for structure, patterns for layouts. It is tempting to conclude that block themes need no PHP at all, and many small ones really do ship without any. But functions.php is still allowed in a block theme, and a few jobs are best done there: registering block styles, loading CSS only when a block is used, adjusting the HTML that a block prints, and adding theme features that have no JSON setting.

This lesson shows those jobs, explains the render_block filter in depth, and ends with a rule of thumb: reach for PHP last, and keep it small. You should know hooks from Actions and Filters and the theme layout from Block Themes: The Big Picture.

When you still need PHP

Try the declarative route first. If any of these describes your task, PHP is the right tool:

  • Registering an extra block style (a named variant such as "Outline" for the Button block).
  • Loading a stylesheet only on pages that use a given block.
  • Changing the front-end HTML of a block, for example adding a class or wrapping an image.
  • Registering block patterns, post types or REST routes (these belong in a plugin if the site should keep them when the theme changes).
  • Adding theme supports that do not exist in theme.json.

Anything that is purely about colors, spacing, fonts or layout belongs in theme.json instead, as covered in theme.json. Settings there are visible and editable in the Site Editor; PHP is not.

functions.php in a block theme

A block theme's functions.php works exactly like the one in a classic theme: it loads on every request, and you attach callbacks to hooks. The conventions are the same too: prefix your function names, and never run logic at the top level of the file. A typical file is short.

PHP
<?php
/**
 * Northwind block theme functions.
 */

if ( ! function_exists( 'northwind_setup' ) ) {
	function northwind_setup() {
		add_theme_support( 'wp-block-styles' );
		add_editor_style( 'assets/css/editor.css' );
	}
}
add_action( 'after_setup_theme', 'northwind_setup' );

wp-block-styles loads the core block stylesheets for the front end, and add_editor_style() loads your own stylesheet inside the editor so what authors see matches the site. Features such as title-tag are enabled automatically for block themes, so you do not need to declare them again.

Registering block styles

A block style is a named variation of one block that authors pick in the sidebar, for instance a second look for the Button. It is just an extra CSS class on the block, in the form is-style-{name}.

PHP
add_action( 'init', function () {
	register_block_style( 'core/button', array(
		'name'  => 'outline-shadow',
		'label' => __( 'Outline with shadow', 'northwind' ),
	) );
} );

That registers the option but supplies no CSS. The stylesheet comes next. (Block styles can also be registered with JSON files in the theme's styles/blocks/ folder in recent WordPress versions, which needs no PHP; the PHP route is still common and always works.)

Loading block CSS only when needed

Loading every block's CSS on every page wastes bytes. wp_enqueue_block_style() attaches a stylesheet to a block so WordPress prints it only when that block is actually rendered on the page.

PHP
add_action( 'init', function () {
	wp_enqueue_block_style( 'core/button', array(
		'handle' => 'northwind-button',
		'src'    => get_theme_file_uri( 'assets/css/button.css' ),
		'path'   => get_theme_file_path( 'assets/css/button.css' ),
	) );
} );

The path argument lets WordPress inline small files and reads the version from the file for cache busting. Compare this with the usual enqueue calls in Enqueuing Styles and Scripts: there you decide per page; here the block's presence decides.

The render_block filter

Every block, when it is turned into HTML on the front end, passes through a filter named render_block. The callback receives the finished HTML string, the parsed block (an array with blockName and attrs) and the block instance, and must return a string.

flowchart LR
    M["Block markup in<br/>post or template"] --> P["Parse into blocks"]
    P --> R["Render each block<br/>(save HTML or render callback)"]
    R --> F["render_block filter"]
    F --> S["render_block_{name} filter"]
    S --> O["HTML in the page"]

After a block makes its HTML, the generic filter and then the block-specific filter can change it.

There is also a block-specific version, render_block_{$name}, such as render_block_core/image, which runs only for that block and is usually the better choice because you do not have to test the name yourself.

PHP
add_filter( 'render_block_core/image', function ( $block_content, $block ) {
	if ( '' === $block_content ) {
		return $block_content;
	}

	$processor = new WP_HTML_Tag_Processor( $block_content );
	if ( $processor->next_tag( 'figure' ) ) {
		$processor->add_class( 'northwind-framed' );
	}

	return $processor->get_updated_html();
}, 10, 2 );

WP_HTML_Tag_Processor is a real core class (WordPress 6.2 and later) that edits HTML safely, tag by tag. It is far more reliable than a regular expression on markup, so use it in real code. Three habits keep render_block callbacks safe:

  1. Always return a string. Returning nothing removes the block's output.
  2. Check what you got. Empty strings and unexpected blocks happen.
  3. Keep it fast. The filter runs once per block per request, which can mean hundreds of calls.

The stand-in below reproduces the mechanism: a block renderer, a render_block filter chain with priorities, and a block-specific filter. It uses a small regex because the real WP_HTML_Tag_Processor is not available here. It is not WordPress code, only the same flow.

PHP A render_block filter stand-in

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.

Look at the order in the output: the priority 5 callback edits the paragraph first, the priority 20 callback adds the comment, and the block-specific filter for images runs last of all. The unknown block produces an empty string and no comment. That mirrors the real behavior of filter priorities from the hooks chapter.

Other useful block hooks

Core exposes several more places to adjust blocks without editing them:

Hook Purpose
register_block_type_args Change a block type's settings (such as its supports) when it is registered.
block_type_metadata Alter the block.json data of a block before it is registered.
render_block_data Change the parsed block (including its attributes) before it renders.
allowed_block_types_all Restrict which blocks authors can insert.

Use them sparingly, and check the current developer documentation for the exact signatures because they have grown over time. Some individual core blocks also have their own named filters; if you need one, look it up in the documentation for that block rather than guessing.

A rule of thumb

Keep the theme's PHP presentation-only. Behavior that should survive a theme switch (custom post types, shortcodes, block registration) belongs in a plugin, which you will build in Your First Plugin. A theme that contains business logic locks the client in; a theme with a few dozen lines of functions.php is easy to maintain.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which function loads a stylesheet only when a particular block appears on the page?

    wp_enqueue_block_style() ties a stylesheet to a block, so WordPress prints it only when the block is rendered.
  2. 2. What must a render_block callback do?

    render_block is a filter, so the callback must return the HTML string. Returning nothing removes the block's output.
  3. 3. What does register_block_style('core/button', ['name' => 'outline-shadow', ...]) add?

    It registers a style option for the block; authors pick it and the block gets an is-style-{name} class. You still supply the CSS.
  4. 4. Which tool should real code use to add a class to a block's HTML safely?

    WP_HTML_Tag_Processor edits HTML tag by tag and is more reliable than regular expressions on markup.
  5. 5. Where should features that must survive a theme switch, such as custom post types, live?

    A theme switch removes theme code, so lasting behavior belongs in a plugin.

Summary

  • Block themes can have functions.php, but use PHP only for what JSON cannot do.
  • register_block_style() adds a selectable style; wp_enqueue_block_style() loads CSS only when the block is used.
  • render_block and render_block_{name} let you change a block's HTML; always return a string and prefer WP_HTML_Tag_Processor.
  • Hooks such as register_block_type_args and allowed_block_types_all adjust blocks without editing them.
  • The TryIt is a stand-in for the filter flow, not WordPress itself.
  • Put durable behavior in a plugin, not the theme.

Next up: Your First Plugin.