How to get all attributes of a block in PHP?

I don’t believe you can. Not easily anyway. I’m happy to be corrected, but this is my understanding of the issue:

Blocks can store their attribute in several ways. They can be stored as JSON inside the block comment, like this example from the documentation:

<!-- wp:latest-posts {"postsToShow":4,"displayPostDate":true} /-->

These are the attributes that are likely accessible in PHP, because they can be parsed with parse_blocks().

But, most other blocks, including the image block, reconstruct their attributes by parsing the HTML. In this other example, no attributes are specified in the block comment. There is only the final HTML:

<!-- wp:image -->
<figure class="wp-block-image"><img src="https://wordpress.stackexchange.com/questions/360257/source.jpg" alt="" /></figure>
<!-- /wp:image -->

For blocks like this, the attributes are reconstructed from the HTML. The logic to do this is only available in block.json, and looks like this:

"url": {
    "type": "string",
    "source": "attribute",
    "selector": "img",
    "attribute": "src"
},
"alt": {
    "type": "string",
    "source": "attribute",
    "selector": "img",
    "attribute": "alt",
    "default": ""
},

That tells the block that the alt attribute can be found by looking for the alt attribute of the img tag in the block, and the url attribute can be found by looking at the src attribute. You can see some of the ways block attributes are found here.

In your example you’ll notice that the attributes that you do have access to are values that are not otherwise stored in the HTML of the block.

So for many blocks, the logic for reconstructing the attributes for editing/modification is only defined in the JavaScript for that block. This logic does not exist in PHP.

If you need to access these attributes from PHP, you will need to parse them out of the HTML yourself. The logic for this will be different for every block.

tech