I need to grab the_content()
via an AJAX request and render all Gutenberg blocks with their inline styling in the page.
Problem is, unique block classes are added to the footer in theme templates.
.wp-container-5 {
display: flex;
gap: 2em;
flex-wrap: nowrap;
align-items: center;
}
When get_the_content()
is used via an AJAX request, that unique block styling isn’t rendered. I would guess this is because the inline block styling relies on a hook of some sort that doesn’t get fired with an AJAX request. do_blocks()
does not render the inline styling.
I’ve searched the database and scoured the WordPress source files and cannot find where classes like .wp-container-5
are coming from. I thought if I could find the location of the inline styling, I could simply query it and render it in the page.
Does anyone know where the unique block styles are stored and/or how to query them and include them via an AJAX request?
2
Answers
I managed to solve this after many hours of frustration.
In
wp-includes/block-supports/layout.php
there is a function calledwp_render_layout_support_flag()
. This function takes a block's content and a block object and assigns the unique classwp-container-
with a unique ID at the end. It then renders the inline styling with the functionwp_get_layout_style()
and enqueues that styling withwp_enqueue_block_support_styles()
.Problem is,
wp_render_layout_support_flag()
doesn't return the styling. It returns the block content with CSS classes and inserts the styling into the footer with CSS classes that match. So, it's not as simple as just callingwp_get_layout_style()
because a unique ID is assigned inwp_render_layout_support_flag()
that is only matched whenwp_get_layout_style()
is called inside thewp_render_layout_support_flag()
function.The solution was to copy and paste (not ideal but it works) the
wp_render_layout_support_flag()
function and slightly alter it.The only change is near the end where
wp_enqueue_block_support_styles()
was removed and now styling and content are returned.Now, Gutenberg blocks can be rendered and have the proper styling when using an AJAX call!
This solution feels kind of ridiculous but it works... WordPress really should support the rendering of blocks asynchronously.
I have not tested this within the response from an AJAX request using the old
admin-ajax.php
method, however, I had been trying to accomplish this same thing within a response from the REST API.Having found this thread and reading over the solution provided by Myles — thanks for your details, btw — and looking into the
wp_render_layout_support_flag
function a bit more, I came up with a potential alternative.Generically, with the REST API, you could add something like this:
You’d probably want to strip out non-style content in the result, in the event you have other functions pushing content that would appear within
wp_footer
.Perhaps something like this would get you what you are looking for: