Yes, it is possible to insert an existing pattern in a WordPress page via PHP and shortcodes. This approach can help prevent your editor from slowing down or crashing by deferring the loading of the pattern until it’s rendered on the front end, rather than during the editing process.
1. Register a Shortcode in WordPress with below code
// Register the shortcode
function insert_pattern_via_shortcode() {
// Check if the function
do_blocks()
exists
if ( function_exists( 'do_blocks' ) ) {
// Replace 'my-pattern-slug' with your pattern's slug
$pattern = get_block_pattern( 'my-pattern-slug' );
if ( $pattern ) {
return do_blocks( $pattern['content'] );
}
}
return '';
}
// Add the shortcode
add_shortcode( 'insert_pattern', 'insert_pattern_via_shortcode' );
2. Using the Shortcode in Pages/Posts
Once the shortcode is registered, you can use it in your pages or posts to insert the desired pattern. Simply add the following shortcode where you want the pattern to appear:
[insert_pattern]
How it Works:
- The shortcode defers the pattern loading until the page is rendered on the front end.
- The?
get_block_pattern()
?function retrieves the content of the block pattern by its slug (replace?'my-pattern-slug'
?with the actual slug of the pattern you want to insert).
- The?
do_blocks()
?function processes the pattern’s block content, which ensures it is properly rendered.