wordpresswordpress-gutenberggutenberg-blockscreate-guten-block

How to get the site root URL when using Wordpress gutenberg wp object


I just created my first gutenberg block plugin using the npm package create-guten-block.

The edit function looks like the code you see below. But it gives a 404 not found on the apiFetch() call because the website lives in a folder, not in the root of the domain. In other words: The structure of the hostname is http://localhost/websitename/ not websitename.local.

edit: ( props ) => {
    if ( ! props.attributes.categories ) {
        wp.apiFetch( {
           url: '/wp-json/wp/v2/categories'
        }).then(categories => {
            props.setAttributes( {
                categories: categories
            });
        });
    }
    return (
        true
    );
}

So what would be the equivalent to PHP's get_site_url()? Is that data somewhere stored in the wp object? If so, where? Because I need to prepend /wp-json/wp/v2/categories with the right site URL.


Solution

  • Just found the solution myself.

    In the init hook of your Gutenberg block plugin you can have a function that creates a global data object for you to use in the Wordpress editor file block.js.

    So, in init.php inside of the init hook you could add:

    wp_localize_script(
        'custom_block',
        'cs_data',
        [
            'siteUrl'       => get_site_url()
        ]
    );
    

    This way the global object cs_data is available in block.js. So the Fetch call could use the dynamic path now like this.

    wp.apiFetch( {
        url: cs_data.siteUrl + '/wp-json/custom-data/v1/post-types'
    } ).then( postTypes => {
        props.setAttributes( {
          postTypes: postTypes
        } );
    } );
    

    Hope this helps.