Skip to content

Instantly share code, notes, and snippets.

@JustinSainton
Created May 30, 2019 21:56
Show Gist options
  • Save JustinSainton/f69c97ca6e034cc23cc937f87d6f3659 to your computer and use it in GitHub Desktop.
Save JustinSainton/f69c97ca6e034cc23cc937f87d6f3659 to your computer and use it in GitHub Desktop.
Sample block Parser
<?php
/**
* Class: Sample_Block_Parser
*
* @package Sample
* @subpackage sample-project
* @since 1.0.0
*/
add_filter(
'block_parser_class',
function() {
return __NAMESPACE__ . '\\Sample_Block_Parser';
}
);
/***
* Specialized block serialization parser
*/
class Sample_Block_Parser extends \WP_Block_Parser {
/**
* Blocks that could be last
*
* @var array
*/
public static $allowed_inner_blocks = [
// Classic blocks have their blockName set to null.
null,
'core/freeform',
'core/heading',
'core/html',
'core/list',
'core/media-text',
'core/paragraph',
'core/preformatted',
'core/pullquote',
'core/quote',
'core/table',
'core/verse',
'core/columns',
];
/**
* Parse document to get a list of block structures
*
* @param string $document Input document being parsed.
*/
public function parse( $document ) {
$this->document = $document;
$this->offset = 0;
$this->output = array();
$this->stack = array();
$this->empty_attrs = json_decode( '{}', true );
// phpcs:disable Generic.CodeAnalysis.EmptyStatement
do {
// twiddle our thumbs.
} while ( $this->proceed() );
// phpcs:enable
return $this->process_output();
}
/**
* Put Article tags at the end
*/
public function process_output() {
$last_block_key = 0;
$article_tags = sample_article_tags();
if ( ! is_array( $this->output ) ) {
return $this->output;
}
foreach ( $this->output as $index => $block ) {
if ( ! isset( $block['blockName'] ) ) {
continue;
}
if ( in_array( $block['blockName'], self::$allowed_inner_blocks, true ) ) {
$last_block_key = $index + 1;
}
}
if ( $last_block_key ) {
$this->output[ $last_block_key ]['innerHTML'] = $article_tags . $this->output[ $last_block_key ]['innerHTML'];
$this->output[ $last_block_key ]['innerContent'][0] = $article_tags . $this->output[ $last_block_key ]['innerContent'][0];
}
return $this->output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment