2

I am creating some posts via the wp_insert_post() function. When doing so the content gets saved in one big classic block. Is there anyway to force it to save as individual Paragraph blocks instead?

3
  • 1
    Does the content only contains simple <p> and </p> paragraphs tags, without any attributes ?
    – birgire
    Commented May 13 at 17:44
  • 2
    I think you'd have to apply the Block markdown for that to happen. If you generate a post in the Block Editor, that's similar to what you'd like yours to be, you can then View HTML/Source and you'll see that there's a markdown and series of HTML classes that get applied. You'll want to apply that to your content and then use something like this stackoverflow.com/a/6380504 to sniff out and segment all of the paragraphs, then loop through them adding the WP markdown and <p> tags with classes to it. Commented May 13 at 17:47
  • 1
    @birgire It originally did. The content was produced via email so it had a lot of mso classes etc. I ended up stripping out all html then used wpautop() to force it to have generic <p> tags.
    – Tommizzy
    Commented May 14 at 13:08

1 Answer 1

1

I ended up writing a function that wraps the <p> tags in the block comments. This forced the content to be individual paragraph blocks in the editor. My content was only paragraphs but other block types would need to be implemented as well.

function blockify_content($content) {
    //remove empty <p>
    $pattern = "/<p[^>]*><\\/p[^>]*>/";
    $content = preg_replace($pattern, '', $content);

    //add block comments
    $search = array('<p', '</p>');
    $replace = array('<!-- wp:paragraph --><p', '</p><!-- /wp:paragraph -->');
    $content = str_replace($search, $replace, $content);
    return $content;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.