Basically we will talk about wp.blocks.parse!
wp.data.select('core/editor').getEditedPostContent();
is used to get the value by HTML comments from the editor.
Let’s create a new post by going into wp-admin. Now use some block in the editor. Now open inspect element by right-clicking and go to console and run the following command.
wp.data.select('core/editor').getEditedPostContent();
Notice that:
In our HTML, Before and after each block we have some sort of an HTML comment. This is called limitors.
They are used to marking this start and end of each block.
Now run following command in console of browser:
wp.blocks.parse(wp.data.select('core/editor').getEditedPostContent());
It will parse all the HTML content into JavaScript objects by using the HTML Comments separator.
Now the question is that, How does it know attributes?
In the comment, we have a JSON object and that object can contain some attributes.
Example:
For Image block
<!-- wp:image {"id":9} -->
In the object’s attributes property, there are some attributes Like
attributes:
alt: ""
caption: ""
id: "9"
url:"xyz.com/image.jpg"
So, Here the image id is stored in JSON Object, and other attributes it extracted from the HTML attributes.
What needed to store in JSON Object?
Sometimes we have attributes that can not be stored in HTML. Like in Image Block: Image ID
So in that case, we have to store ID in JSON object comment. this way we let parser knows that the all the attribute that we have.
Now Let’s see how data is serialized by doing some manual stuff.
Run:
wp.blocks.serialize( wp.blocks.parse( wp.data.select( 'core/editor' ).getEditedPostContent() ) );
So, It will return a new HTML that WordPress saves in the database.
Leave a Reply