I have no idea if this is even possible, but I am trying it anyway.
I have created a plugin where I want to load all my pre-designed patterns from in wordpress.
My plugin contains the following code (used to register my patterns)
function register_my_pattern() {
register_block_pattern(
'my-plugin/my-pattern',
array(
'title' => __( 'My Pattern Name', 'my-plugin' ),
'categories' => array('my-pattern-category'),
'content' => '<!-- wp:group {"backgroundColor":"vivid-green-cyan","layout":{"type":"constrained"}} --> <div class="wp-block-group has-vivid-green-cyan-background-color has-background"><!-- wp:heading --> <h2 class="wp-block-heading">Testing my block</h2> <!-- /wp:heading --></div> <!-- /wp:group -->',
)
);
}
add_action( 'init', 'register_my_pattern' );
The problem is that the content gets quite long for some patterns and I want an easy way edit them . I hate the fact that I need to minify my code to load it through register_block_pattern.
I would really like to put the actual content of the patterns in a seperate file and load it from there instead (so I don’t have to minify them, and so that I can easily edit them).
So I tried doing this:
but this just prints the URL of the file when adding the pattern in the editor
function register_my_pattern() {
register_block_pattern(
'my-plugin/my-pattern',
array(
'title' => __( 'My Pattern Name', 'my-plugin' ),
'categories' => array('my-pattern-category'),
'content' => plugin_dir_url( __FILE__ ).'my-pattern-file.php',
)
);
}
add_action( 'init', 'register_my_pattern' );
I also tried this:
But this loads the content when opening the editor (even if the block isn’t added)
function register_my_pattern() {
register_block_pattern(
'my-plugin/my-pattern',
array(
'title' => __( 'My Pattern Name', 'my-plugin' ),
'categories' => array('my-pattern-category'),
'content' => include( plugin_dir_path( __FILE__ ) . 'my-pattern-file.php'),
)
);
}
add_action( 'init', 'register_my_pattern' );
Is there any way to do this? Or is this completely impossible?
2
Answers
You can register block patterns defined in PHP files by including them in the patterns directory in a block theme (NB. WordPress version 6.0+).
Although this is not a plugin-based solution like your example, it keeps the block pattern as PHP and part of the theme. The
*.php
pattern files are placed inyour-theme-name/patterns/
and automatically loaded into the Editor when the theme is active.Include the pattern and capture in the output buffer, then use that string in the register block pattern function. it’s not great and could probably get slow. I hope in the future they make a function that can handle this and read the pattern header.