Hi there,
I built a custom dynamic block that calls the WordPress PHP function get_the_ID() in render.php. The custom block works fine on the public face of the site. When the custom block is inserted into a view created via the block editor, however, it doesn't work correctly. The reason is that get_the_ID() returns the ID of the current View, not the ID of the post in the view's loop.
My short-term solution is to identify the post type of the given ID and ignore the post type "view-template" (and "revision," another post type the block editor uses). Does Toolset recommended another approach to handle this? How can I obtain the "correct" post ID?
Thank you.
Saul
Hi Saul,
Thank you for the details.
Inside a Toolset View loop, get_the_ID() can return the View/template context instead of the current loop item in some block-rendering contexts. This is expected with server-side rendered custom blocks because the block render callback may not always inherit Toolset’s loop post context.
Recommended way to get the current post in a View loop is to use Toolset’s own current-loop shortcodes, for example:
This shortcode is designed to output the ID of the current post in the View loop. For more information:
https://toolset.com/documentation/programmer-reference/views/views-shortcodes/#wpv-post-id
If your custom block needs that ID in PHP, the safer approach is to pass the ID into the block as an attribute, or use a shortcode wrapper/custom shortcode where [wpv-post-id] is passed as the value.
For more information on custom shortcodes:
https://toolset.com/documentation/programmer-reference/adding-custom-code/how-to-create-a-custom-shortcode/
So instead of relying on get_the_ID() inside the custom block render file, I recommend passing the current View loop post ID explicitly from the View context:
[my-custom-output post_id="[wpv-post-id]"]
I did not test the approach, but I thought I would share this to give you an idea.
Thanks.
Hi Christopher,
Thanks for your response. I attempt to use the [wpv-post-id] shortcode in the context of the block editor, and it didn't work. It returned the ID of the view template. But my work-around is fine, so we'll just leave this here in case someone else encounters the issue. (Or should this be filed as a known issue?)
Saul