1

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 } = ????;
}

1 Answer 1

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>
);
2
  • PS: { autoupdate } is a shorthand for { autoupdate: autoupdate }.
    – Sally CJ
    Commented Jan 31 at 5:02
  • Wow thank you! I will try that and report
    – Marc
    Commented Jan 31 at 6:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.