Skip to content

Instantly share code, notes, and snippets.

@vanaf1979
Created March 24, 2021 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vanaf1979/c5651a9f6392260aeeb74ead7a69473c to your computer and use it in GitHub Desktop.
Save vanaf1979/c5651a9f6392260aeeb74ead7a69473c to your computer and use it in GitHub Desktop.
Are blocks rendered yet
<?php
final class RenderedBlocks {
/**
* instance.
*
* @var RenderedBlocks $instance class instance.
*/
private static $instance = null;
/**
* rendered_blocks.
*
* @var array $rendered_blocks store all the blocks that have been rendered
*/
private $rendered_blocks = null;
public function __construct()
{
$this->init();
}
/**
* instance.
*
* Return an instance of this class if it exists, else create it and return it..
*
*/
public static function instance(): RenderedBlocks
{
if (!isset(self::$instance) && !(self::$instance instanceof \RenderedBlocks)) {
self::$instance = new Self();
}
return self::$instance;
}
/**
* init
*
* Register to the pre_render_block filter, to store all the blocks that have been rendered
*
* @uses pre_render_block https://developer.wordpress.org/reference/hooks/pre_render_block/
* @uses add_filter https://developer.wordpress.org/reference/functions/add_filter/
*
*/
public function init()
{
add_filter('pre_render_block', array($this, 'cache_rendered_blocks'), 2, 2);
}
/**
* cache_rendered_blocks
*
* Callback for the pre_render_block filter.
* Push all rendered blocks to the rendered_blocks array.
*
*/
public function cache_rendered_blocks($parsed_block, $source_block)
{
$this->rendered_blocks[] = $source_block;
}
/**
* is_block_rendered
*
* Check if a block of a certain type has been rendered on the page yet
*
*/
public function is_block_rendered($block_name)
{
foreach ($this->rendered_blocks as $block) {
if ($block['blockName'] == $block_name) {
return true;
}
}
return false;
}
/**
* print_rendered_blocks
*
* Utility: Print.r all the rendered blocks.
*
*/
public function print_rendered_blocks()
{
echo '<pre>';
print_r($this->rendered_blocks);
echo '<pre>';
}
}
/**
*
* Initialize the class on WordPress init
*
*/
add_action('init', function () {
$inst = RenderedBlocks::instance();
})
?>
<?php
/**
*
* Somewhere in your code you can check if a certain block has been rendered yet.
*
*/
( RenderedBlocks::instance() )->is_block_rendered('core/heading');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment