Forum Replies Created

Viewing 1 replies (of 1 total)
  • Thread Starter strongerphilip

    (@strongerphilip)

    Okay! 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 from block.json within the render.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 the source 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 the source 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.json

    So 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.

Viewing 1 replies (of 1 total)