I am writing a plugin for the Gutenberg editor.

I know how to use editPost() to change e.g. some meta-values:

editPost( {
    meta: {
         myMeta: 'new meta value goes here'
    }
} );

This is working fine.

But when I try to change the post status, e.g. I want to unpublish a post:

editPost( {
    status: 'draft' // <-- this does not work
} );

There are several other functions, such as savePost() or trashPost(). I could not find anything to publish or unpublish a post.

How can I change the post status within a custom Gutenberg-plugin?

1 Answer
1

You need to call savePost after calling editPost. Referring to the source’s way of handling it:https://github.com/WordPress/gutenberg/blob/trunk/packages/editor/src/components/post-visibility/index.js it shows savePost being called right after changing the visibility.

In practice:

import { PluginPostStatusInfo } from '@wordpress/edit-post';
import { __ } from '@wordpress/i18n';
import { registerPlugin } from '@wordpress/plugins';
import { ToggleControl } from '@wordpress/components';
import { useSelect, useDispatch } from '@wordpress/data';

function PostChangeToggle() {
    const status = useSelect( ( select ) => {
        return select( 'core/editor' ).getEditedPostAttribute( 'status' );
    }, [] );

    const { editPost, savePost } = useDispatch( 'core/editor' );

    return (
        <PluginPostStatusInfo
            name="prefix-post-change"
            title={ __( 'Post Change', 'text-domain' ) }
            className="prefix-post-change"
            initialOpen={ true }
        >
            <ToggleControl
                label={ __( 'Draft', 'text-domain' ) }
                checked={ status === 'draft' }
                onChange={ () => {
                    editPost( {
                        status: status === 'draft' ? 'publish' : 'draft',
                    } );
                    savePost();
                } }
            />
        </PluginPostStatusInfo>
    );
}

registerPlugin( 'prefix-post-change', {
    render: PostChangeToggle,
} );

The code above will create a simple toggle back and forth from draft and publish. You can swap out ‘draft’ or another status or a custom status. I have an “expired” status that I control in a similar fashion.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *