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
Add a comment  | 

1 Answer 1

Reset to default 3

If 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