admin管理员组文章数量:1279187
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?
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?
Share Improve this question asked Sep 30, 2021 at 6:26 urukuruk 6348 silver badges22 bronze badges1 Answer
Reset to default 1You need to call savePost after calling editPost. Referring to the source's way of handling it:https://github/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.
本文标签: block editorGutenberg How to Change Post Status Programmatically
版权声明:本文标题:block editor - Gutenberg: How to Change Post Status Programmatically? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741276846a2369778.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论