I think the issue you will run into here is that markup from the save function is created at post edit. The attributes like that link.url
you reference will be correct at time of save – which is where the JS runs – but not necessarily at render if the post attributes have been changed.
The only way I can think of to change this at block render without PHP render would be to store your ID as a data-attribute against the anchor. Something like:
<a href="#" data-post-id="234" data-rest-route="posts">Link Content</a>
Where data-post-id
is obviously the post ID and data-rest-route
is the rest route or the parameter from the rest_base
when you set up the posts with register_post_type()
This you can parse from the initial post query return (the bit where you get the slug in your un-posted code to add to the .link.url
on the block)
You can then run a secondary JS script on page load that leverages the REST API to get the correct slug at time of render.
Your URL path will be something like
/wp-json/wp/v2/{post_type}/{ID}
or to match the above example /wp-json/wp/v2/posts/234
Then take the slug from the JSON object on page load to inject into the link href.
It’s a bit of a workaround… And I wouldn’t use this in public plugin code, as you have no idea how or if the rest API has been allowed or modified on custom post types for other setups.