• Hello,

    I’ve been hitting my head on walls for a few weeks now, trying to modify post content with a plugin.

    Context : translation plugin. Gets title, excerpt and content, translates via API and update title, excerpt, content with the resulting strings.
    Translation do no touch <– wp xxxx –> tags (they are in the source and the result HTML code)

    Title is simple :
    wp.data.dispatch( 'core/editor' ).editPost( { title: new_title} )

    Excerpt is simple :
    wp.data.dispatch( 'core/editor' ).editPost( { excerpt: new_excerpt } )

    Post content is a major pain.
    I wish it was :
    wp.data.dispatch('core/editor').editPost( {content: new_content });

    but that doesn’t work due to blocks getting in the way.

    Right now, I’m exploding the translated post content into more or less blocks.
    Using :

    var newBlock = wp.blocks.createBlock( "core/paragraph", { content: content});
    var inserted = wp.data.dispatch( "core/block-editor" ).insertBlocks( newBlock );

    works more or less with paragraph blocks, but derails with image/heading blocks.

    Is there a way to just dump the new post content into the current editor ?
    If not, is there a recommended way to parse content with <– blocks –> and insert them into the editor ?

    Thanks for your help

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter malaiac

    (@malaiac)

    I’m gonna up this one, because I’m still struggling to find a simple way to edit the whole post_content.

    Right now, I’m updating block by block that proves to be trickier than expected. Gutenberg wants to add paragraph tags around blocks, creating messy HTML soup.
    ie splitting new content into paragraphs, then inserting block content with :

    var newBlock = wp.blocks.createBlock( "core/paragraph", {
    				    					content: content
    									});

    creating paragraphs (hence the p tags around blocks)

    I’ve tried :

    const currentPost = wp.data.select( 'core/editor' ).getCurrentPost();
    		wp.data.dispatch( 'core' ).editEntityRecord( 'postType', currentPost.type, currentPost.id, { 'post_content': "test post content" } );

    without success

    Any idea ?

    You can reset the post and insert only strings.

    wp.data.dispatch( 'core/editor' ).resetBlocks( wp.blocks.parse( 'My content' ) );

    You can create blocks and insert them into the content.

    const newBlock = wp.blocks.createBlock( "core/paragraph", {
        content: 'This is the content',
    });
    wp.data.dispatch( "core/editor" ).insertBlocks( newBlock );
    Thread Starter malaiac

    (@malaiac)

    wp.data.dispatch( 'core/editor' ).resetBlocks( wp.blocks.parse( 'My content' ) );

    I lost months looking for this gem !

    Thanks a lot @soean

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Getting and modifying Gutenberg post content with Javascript’ is closed to new replies.