Home > Blockchain >  WordPress when using the wp_update_post function to update the custom post type contents Gutenberg d
WordPress when using the wp_update_post function to update the custom post type contents Gutenberg d

Time:09-04

I have create a custom post type, that I'd like to update the post content using a custom Rest API Endpoint.

The way I update the content of the post is by using the function wp_update_post.

So far all work perfect. My actual issue is that when I open the post from the dashboard, the Gutenberg editor display the post contents using the block Classic like the following screenshot.

So I was wondering if there is any WordPress function that can convert the plain HTML I have from my front end client to Gutenberg blocks.

I've search a lot, but I cannot find anything. Maybe I have missed something.

For sure, it's not the end of the Word if I don't find a way to convert the plain HTML to Gutenberg blocks, but if I can have this option it will be nice :)

Thank you in advance.

enter image description here

CodePudding user response:

In the Editor, click inside the Classic block to show the context menu then select "Convert to blocks". This action transforms compatible classic content into blocks and works well for simple content like your example into paragraph blocks. Post > Classic

The function that handles the conversion from raw HTML to blocks is serialize, a JavaScript function from the blocks API. I've not found an equivalent core WordPress PHP function (as of 6.0) to convert classic content to blocks, so I wrote a simple one for plain text to be formatted as paragraph blocks, eg:

php

/**
* Convert text to paragraph block markup that parse_blocks() will render
* @see https://developer.wordpress.org/reference/functions/parse_blocks/
*/
function convert_to_paragraph_block($text){
    $content = '';
    $paragraphs = preg_split('/\r\n|\r|\n/', $text); // split text on newline

    foreach($paragraphs as $paragraph){
        $content .= sprintf('<!-- wp:paragraph --><p>%s</p><!-- /wp:paragraph -->', $paragraph);
    }
    
    return $content;
}

If you use the above function to format the incoming content from your REST endpoint, the markup saved in the_content would be:

<!-- wp:paragraph -->
<p>Lorem ipsum ...</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Duis aute ...</p>
<!-- /wp:paragraph -->
  • Related