4

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.

Kelvin Mariano
  • 752
  • 5
  • 15
Floris
  • 1,805
  • 1
  • 17
  • 39

2 Answers2

2

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.

Floris
  • 1,805
  • 1
  • 17
  • 39
-2

Try updating your site_url or home_url

site_url() will always be the live location where you can reach the site wheras home_url() would be where you have set your homepage.

Try setting the home_url() to the "http://localhost/websitename" by visiting and editing the General > Settings "WordPress address (URL)" field.

You could also define the paths programmatically by editing the wp-config.php:

define( 'WP_HOME', 'http://localhost/websitename/' );
define( 'WP_SITEURL', 'http://websitename.local' );

Then you could use get_home_url() to retrieve the correct path.

Kradyy
  • 315
  • 1
  • 4