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
$attributesto be empty.First: Thank you Bernardatis for clarifying how to retrieve the
$attributes! Brilliant 🙂To reiterate:
You can access the
attributesyou’ve created fromblock.jsonwithin therender.phpdirectly 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.jsonstill had thesourceproperty when defining the attributes.The
sourceproperty 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.jsfile, thus making your$attributesempty. So remove thesourceproperty 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 3 years, 5 months ago by strongerphilip.
- This reply was modified 3 years, 5 months ago by strongerphilip.