Last active
November 24, 2018 09:19
-
-
Save AndreKelling/ac4d8be7111d27aaf236460dc5b1800e to your computer and use it in GitHub Desktop.
Dynamic Gutenberg WP Block RichText Component Rendering (until Gutenberg 4.5.1)
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 | |
/** | |
* help rendering the richText Component saved object | |
* was needed when RichText saved as array. Since Gutenberg 4.5.1. RichText saves in string! | |
* | |
* no dynamic nice rendering provided https://github.com/WordPress/gutenberg/projects/14#card-11206239 | |
* | |
* @since x.x.x | |
* @param $arr object from the JS RichText Component | |
* @return string Rendered HTML | |
*/ | |
function richtextRender($arr) { | |
$out = ''; | |
if (is_array($arr)){ | |
foreach ($arr as $line){ | |
$out .= richtextRenderLoop($line); | |
} | |
} else { | |
$out = richtextRenderLoop($arr); | |
} | |
return $out; | |
} | |
function richtextRenderLoop($lines) { | |
$out = ''; | |
if (is_array($lines)){ | |
if (empty( $lines['props']['children'] ) ) { | |
$out .= '<' . $lines['type'] . '/>'; | |
} else { | |
// opening tag | |
$out .= '<' . $lines['type']; | |
if (!empty( $lines['props']['href'] )){ | |
$out .= ' href="'.$lines['props']['href'].'"'; | |
} | |
if (!empty( $lines['props']['target'] )){ | |
$out .= ' target="'.$lines['props']['target'].'"'; | |
} | |
$out .= '>'; | |
// nesting tag | |
foreach ($lines['props']['children'] as $line) { | |
$out .= richtextRenderLoop($line); | |
} | |
// closing tag | |
$out .= '</' . $lines['type'] . '>'; | |
} | |
} else { | |
$out .= $lines; | |
} | |
return $out; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment