Hey @chriscoyier,
It’s not possible but you can write a PHP function to scrap the attributes of blocks, like this: https://github.com/Codeinwp/gutenberg-css/blob/master/class-gutenberg-css.php#L131
You can use this function ^ to hook the CSS into the REST API with https://developer.wordpress.org/reference/functions/register_rest_field/.
I wrote this roughly but it works:
add_action( 'rest_api_init', 'add_post_css_rest_field' );
function add_post_css_rest_field() {
register_rest_field( 'post', 'customCSS', array(
'get_callback' => 'get_post_css',
'schema' => null,
)
);
}
function get_post_css( $object ) {
//get the id of the post object array
$post_id = $object['id'];
if ( class_exists( '\ThemeIsle\GutenbergCSS' ) ) {
$content = get_the_content( $post_id );
$content = parse_blocks( $content );
if ( ! is_array( $content ) || empty( $content ) ) {
return null;
}
$class = new \ThemeIsle\GutenbergCSS();
$css = $class->cycle_through_blocks( $content );
if ( ! empty ( $css ) ) {
return $css;
}
}
return null;
}
This will add a customCSS field to Rest API with all the CSS. Let me know if it helps.
And keep the good work up, learned a lot from you! 🙂
Hey @hardeepasrani,
Nice! This is SO CLOSE to working! The part about getting the Custom CSS into the REST API works, but then then the problem is that the HTML in the REST API doesn’t have the class names that match on it.
So in the editor, say you have an image that ends up like…
<figure class="wp-block-image ticss-bfb6cec0 size-large">
With customCSS that ends up like…
.ticss-bfb6cec0 { border: 2px solid red; }
The REST API only has
<figure class="wp-block-image size-large">
So the customCSS doesn’t apply. Is there a way to filter the REST API to have the class names that this plugin applies?
Hey @chriscoyier,
I tried this on my end and the classes also appear in REST response, as you can see here: https://pasteboard.co/JcNJRir.png or live at this demo link: https://round-palm.jurassic.ninja/wp-json/wp/v2/posts/1
Let me know how it goes on your end! 🙂
Oooo yep, the classes ARE in there, thank you!
You’re welcome, @chriscoyier. I’m marking this as resolved. Thank you for using our plugin. I hope you enjoy using it as much as we enjoy making it. 🙂