Last active
January 10, 2020 19:58
-
-
Save adam-laita/048952be66eb44d5a7040c744c71b043 to your computer and use it in GitHub Desktop.
WordPress - Gutenberg -> Custom image block (render_block hook)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// php library Simple HTML DOM Parser https://simplehtmldom.sourceforge.io/ (required) | |
require_once __DIR__ . '/simple-html-dom.php'; | |
// rewrites core-image block with custom HTML | |
add_filter( 'render_block', 'my_block_core_image', 10, 2 ); | |
function my_block_core_image( $block_content, $block ) { | |
// specify image block | |
if ( $block['blockName'] === 'core/image' ) { | |
// this dump of image block HTML will help you with parsing (just for example) | |
var_dump( $block_content ); | |
// create a DOM object from a string | |
$html = str_get_html( $block_content ); | |
// finds the first required element and saves it to variable, if not returns null | |
$figure = $html->find( 'figure', 0 ); | |
$link = $html->find( 'a', 0 ); | |
$img = $html->find( 'img', 0 ); | |
$caption = $html->find( 'figcaption', 0 ); | |
// turns on output buffering | |
ob_start(); | |
// gets attributes from specified elements | |
?> | |
<figure class="<?php echo $figure->class; ?>"> | |
<?php | |
if ( $link ) { | |
echo '<a href="' . $link->href . '">'; | |
} | |
?> | |
<img class="<?php echo $img->class; ?>" src="<?php echo $img->src; ?>" alt="<?php echo esc_attr( $img->alt ); ?>"> | |
<?php | |
if ( $link ) { | |
echo '</a>'; | |
} | |
if ( $caption ) { | |
?> | |
<figcaption> | |
<?php | |
echo $caption->innertext; | |
?> | |
</figcaption> | |
<?php | |
} | |
?> | |
</figure> | |
<?php | |
// returns the content of output buffering | |
return ob_get_clean(); | |
} | |
// returns other blocks | |
return $block_content; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment