admin管理员组文章数量:1125576
I use a global settings menu in WordPress for my plugin. I use update_option to set some options there. How do I use or retrieve these options in Gutenberg e.g. the edit.js ? Or can I set block attributes in php somehow?
For example I have an option called "autoupdate"
<?php update_option('autoupdate', true); ?>
How do I retrieve this option in the default function in react:
export default function Edit( { attributes, setAttributes } ) {
const { autoupdate } = ????;
}
I use a global settings menu in WordPress for my plugin. I use update_option to set some options there. How do I use or retrieve these options in Gutenberg e.g. the edit.js ? Or can I set block attributes in php somehow?
For example I have an option called "autoupdate"
<?php update_option('autoupdate', true); ?>
How do I retrieve this option in the default function in react:
export default function Edit( { attributes, setAttributes } ) {
const { autoupdate } = ????;
}
Share
Improve this question
asked Jan 30, 2024 at 19:52
MarcMarc
6979 silver badges28 bronze badges
1 Answer
Reset to default 3If your option is enabled in the REST API, e.g. by using register_setting()
with 'show_in_rest' => true
, you can use wp.data.select( 'core' ).getSite()
to retrieve the value of your option, and to update the option, you can use wp.data.dispatch( 'core' ).saveSite()
.
So for example in your case:
To get the option value:
wp.data.select( 'core' ).getSite()?.autoupdate
To update the option (to
true
):wp.data.dispatch( 'core' ).saveSite( { autoupdate: true } )
Note: This function will make an AJAX request to the Site Settings endpoint, so you will need to wait a while before
getSite()
returns the updated options.
Example using useSelect
and useDispatch
in the edit
function:
// In the `edit` function:
// Get the current option value.
const autoupdate = useSelect(
( select ) => select( 'core' ).getSite()?.autoupdate,
[]
);
// Extract the function which saves the new option value.
const { saveSite } = useDispatch( 'core' );
// Save the new option value.
function saveAutoupdate( autoupdate ) {
saveSite( { autoupdate } );
}
return (
<div { ...useBlockProps() }>
<CheckboxControl
label="Auto-Update"
help="Additional help text"
checked={ !! autoupdate }
onChange={ saveAutoupdate }
/>
</div>
);
本文标签: How to use getoption() in Gutenberg block editor to retrieve global settings
版权声明:本文标题:How to use get_option() in Gutenberg block editor to retrieve global settings? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736669877a1946862.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论