Skip to content

Instantly share code, notes, and snippets.

@rku4er
Last active July 7, 2024 00:28
Show Gist options
  • Save rku4er/2d9904d022d4ebd4fdecc7042589f18e to your computer and use it in GitHub Desktop.
Save rku4er/2d9904d022d4ebd4fdecc7042589f18e to your computer and use it in GitHub Desktop.
Custom utils for retrieving blocks from Wordpress posts content, archives, search, 404, etc.
<?php
/**
* Recursively get blocks and their inner blocks.
*
* @param array $blocks List of blocks.
* @return array Flattened list of all blocks.
*/
function get_blocks_recursive( array $blocks ) {
$result = [];
$slugs = [];
foreach ( $blocks as $block ) {
$result[] = $block;
if( 'core/template-part' === $block['blockName'] ) {
$slugs[] = $block['attrs']['slug'];
} elseif ( ! empty( $block['innerBlocks'] ) ) {
$result = array_merge( $result, get_blocks_recursive( $block['innerBlocks'] ) );
}
}
if( ! empty( $slugs ) ) {
$templates_parts = get_block_templates( [ 'slug__in' => $slugs ], 'wp_template_part' );
foreach ( $templates_parts as $templates_part ) {
if ( ! empty( $templates_part->content ) ) {
$result = array_merge( $result, get_blocks_recursive( parse_blocks( $templates_part->content ) ) );
}
}
}
return $result;
}
/**
* Get all blocks for a given post or current post if no ID is provided.
*
* @param int|null $post_id Post ID.
* @return array List of blocks.
*/
function get_blocks( ?int $post_id = null ) {
global $post, $_wp_current_template_content;
$post_content = '';
$blocks = [];
if ( is_singular() ) {
if( $post_id && has_blocks( $post_id ) ) {
$post_content = get_post_field('post_content', $post_id );
} elseif( ! empty( $post->ID ) ) {
$post_content = get_post_field('post_content', $post->ID );
}
$blocks = get_blocks_recursive( parse_blocks( $post_content ) );
}
if( current_theme_supports( 'block-templates' ) ) {
$blocks = array_merge( $blocks, get_blocks_recursive( parse_blocks( $_wp_current_template_content ) ) );
}
return $blocks;
}
/**
* Example use
*
*/
add_action(
'wp_enqueue_scripts',
function() {
global $post;
$handler = 'custom-styles';
$blocks = array_unique( wp_list_pluck( get_blocks( $post->ID ), 'blockName') );
if( ! empty( $blocks ) && in_array( 'core/myblock', $blocks ) ) {
// Enqueue styles for frontend
if( ! wp_style_is( $handler, 'enqueued') ) {
wp_enqueue_style( $handler );
}
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment