strongerphilip
Forum Replies Created
-
Forum: Developing with WordPress
In reply to: Attributes in a Dynamic Custom BlockOkay! I had two issues in my implementation that was causing the
$attributes
to be empty.First: Thank you Bernardatis for clarifying how to retrieve the
$attributes
! Brilliant ??To reiterate:
You can access the
attributes
you’ve created fromblock.json
within therender.php
directly with$attributes
:// render.php <?php // Extract the 'title' attribute. Fallback to 'unknown'. $title = $attributes['title'] ? $attributes['title'] : 'unknown'; ?> <div> <!-- Echo the title value --> <h2><?= $title ?></h2> </div>
Second: the underlying issue was that my
block.json
still had thesource
property when defining the attributes.The
source
property should NOT be defined when using a dynamic block as it’s only meant for use in a static block.Doing so will prevent your attributes from saving in your
edit.js
file, thus making your$attributes
empty. So remove thesource
property altogether.(I was migrating a static block to a dynamic block and didn’t realize this issue).
Attribute sources are used to define how the attribute values are extracted from saved post content. They provide a mechanism to map from the saved markup to a JavaScript representation of a block.
https://schemas.wp.org/trunk/block.jsonSo don’t do this:
// block.json ... "attributes": { "title": { "type": "string", "source": "text" // <-- THIS IS INCORRECT! } }, ...
Just remove it all together:
// block.json ... "attributes": { "title": { "type": "string" } }, ...
Now your attribute will save, and you should be able to render it in
render.php
.- This reply was modified 2 years, 2 months ago by strongerphilip.
- This reply was modified 2 years, 2 months ago by strongerphilip.