bobbingwide / sb-field-block

Field block to display post meta data
GNU General Public License v3.0
3 stars 0 forks source link

ISBAT: ServerSideRender in a query loop in the block editor and receive the post ID of the post being processed #8

Open bobbingwide opened 1 week ago

bobbingwide commented 1 week ago

When being rendered on the front end the sb-field-block uses the correct post ID to obtain the postmeta data for the post being processed.

In the block editor the post id that is passed for server side rendering is the ID of the post being edited, not the id of a post being displayed in the query loop / post template.

There are a couple of open issues in Gutenberg that seem to cover this problem. The first one, at https://github.com/WordPress/gutenberg/issues/34882, was raised 3 years ago. It contains a potential solution to implement until Gutenberg delivers something.

bobbingwide commented 1 week ago

My workaround to the problem involved the following changes: 69535f4 - add additional parameters to sb_field_block_dynamic_block() to enable tracing of the $block parameter. 724ebd6 - Add "usesContext": [ "postType", "postId" ], to block.json 5cf1f39 - Pass context to DisplayMetaControl in edit.js 2cc1591 - Extract the value of postId from context and pass it to ServerSideRender in urlQueryArgs as post_id.

let urlQueryArgs = { "post_id": props.context.postId };
return(
<ServerSideRender block="oiksb/sb-field-block" attributes={props.attributes} urlQueryArgs={ urlQueryArgs }/>
);

Apart from the change to add the $content and $block parameters to the function that performs server side rendering there were no other server changes required. The value in urlQueryArgs overrides the post_id that would have been passed in the server side rendering request, so we get the post_id of the post being displayed within a query loop.