Template Part Shortcode for Classic Themes
Adds a [wpide_template_part slug="footer"] shortcode that prints a block template part, so classic themes and page builders can reuse parts designed in the Site Editor.
Opens WPIDE on
Code
// Template part slugs that may be used.
$wpide_allowed_parts = array( 'header', 'footer', 'sidebar', 'cta' );
add_shortcode( 'wpide_template_part', function ( $atts ) use ( $wpide_allowed_parts ) {
static $depth = 0;
$atts = shortcode_atts( array( 'slug' => '' ), $atts, 'wpide_template_part' );
$slug = sanitize_key( $atts['slug'] );
if ( ! $slug || ! in_array( $slug, $wpide_allowed_parts, true ) || $depth > 1 || ! function_exists( 'get_block_template' ) ) {
return '';
}
$part = get_block_template( get_stylesheet() . '//' . $slug, 'wp_template_part' );
if ( ! $part || empty( $part->content ) ) {
return '';
}
$depth++;
$html = do_blocks( $part->content );
$depth--;
return '<div class="wpide-template-part wpide-template-part-' . esc_attr( $slug ) . '">' . $html . '</div>';
} );
Notes
Only slugs in the allowed list are rendered. Template parts must exist for the active theme (Appearance > Editor or the Patterns screen).
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.