I am writing a Wordpress plugin to create custom Gutenberg blocks. I am using a composer package called Carbon Fields. But when I try to use the package I am getting an Error:
Fatal error: Uncaught Error: Class 'Carbon_Fields\Block' not found in /my-path/my-plugin/my-plugin.php on line 10.
The strange thing is that I can use the Container and Field classes without problems.
Note
I have just included the basic file structure and code so that you can focus on the important things.
File structure
- my-plugin
- vendor
- htmlburger
- core
- Block.php
- Carbon_Fields.php
- Container.php
- Field.php
- core
- htmlburger
- my-plugin.php
- vendor
Code
my-plugin.php
add_action( 'after_setup_theme', 'carbon_fields_init' );
function carbon_fields_init() {
require_once plugin_dir_path( __FILE__ ) . 'vendor/autoload.php';
\Carbon_Fields\Carbon_Fields::boot();
}
use \Carbon_Fields\Block;
use \Carbon_Fields\Filed;
Block::make( __( 'Hero Image' ) )
->add_fields( array(
Field::make( 'text', 'heading', __( 'Block Heading' ) ),
) )
->set_render_callback( function ( $fields, $attributes, $inner_blocks ) {
?>
<div class="block">
<div class="block__heading">
<h1><?php echo esc_html( $fields['heading'] ); ?></h1>
</div><!-- /.block__heading -->
<?php
} );
Block.php
namespace Carbon_Fields;
class Block extends Container {
public static function make() {
return call_user_func_array( array( 'parent', 'make' ), array_merge( array( 'block' ), func_get_args() ) );
}
}
Finally I got the answer from a portuguese tutorial (https://www.youtube.com/watch?v=bKY-7_wR2n0). I had to wrap the block creation in a function and set that function as a callback for the carbon_fields_register_fields action hook.