Amrit Ray
Amrit Ray

Reputation: 21

How to fetch Options in Gutenberg Editor Edit.js file. There seems no easy way to do this

Fetching Options in a php file in WordPress theme or plugin is as easy as typing:

get_option('option_name');

How do we fetch Options in a Gutenberg block, inside the Edit.js file? Fetching meta value in a Gutenberg block is easy enough. But there seems to be no way to fetch Options from the Options table.

Can someone please tell me how to do this? Thanks.

Upvotes: 1

Views: 29

Answers (1)

S.Walsh
S.Walsh

Reputation: 3699

Options can be retrieved using the hook useEntityProp() which uses apiFetch to call the REST API /wp/v2/settings within the Edit() function. From there, you can use any setting defined in the REST Site Settings schema or custom ones you may have registered, eg:

edit.js

import { useBlockProps } from '@wordpress/block-editor';
import { useEntityProp } from '@wordpress/core-data';

export default function Edit() {
    var setting  = 'timezone'; // Can be any valid setting/option from /wp/v2/settings endpoint
    const [ option ] = useEntityProp( 'root', 'site', setting );

    return (
        <p {...useBlockProps()}>
            {option}
        </p>
    );
}

The Developer Guide for Meta Boxes has a more detailed example of useEntityProp() for getting/updating values in Gutenberg blocks which may be helpful too..

Upvotes: 0

Related Questions