Support Forum
Hi
I have been testing and found it is difficult to pass a unique ID for my carousel library. The library targets a unique DIV ID so each instance of my block will require this ID.
I have included my JS file inside the enqueue_assets and used 'wp_add_inline_script' to send the unique ID to this.
My problem is with 'render_template' as I cannot send the same unique ID across. I have tried using the attributes inside 'render_template' but if I do this then I cant send this across to JS.
I have tried various options but no luck, below is just an example so you get the idea of what I am trying to achieve. I was just wondering if I was missing something obvious?
add_filter( 'rwmb_meta_boxes', function( $meta_boxes ) {
$meta_boxes[] = [
'title' => 'Carousel Block',
'id' => 'dc-carousel-block',
'description' => 'Carousel with product support',
'type' => 'block',
'icon' => 'screenoptions',
'category' => 'dc-blocks',
'context' => 'side',
'render_template' => __DIR__ . '/template/dc-carousel-block-template.php',
'enqueue_style' => plugin_dir_url( __FILE__ ) . 'css/splide.min.css',
'enqueue_script' => plugin_dir_url( __FILE__ ) . 'js/splide.min.js',
'supports' => [
'align' => ['wide', 'full'],
],
'enqueue_assets' => function() {
wp_enqueue_script( 'splide-custom-script', plugin_dir_url( __FILE__ ) . 'js/splide-run.js', [], '1', true );
wp_add_inline_script( 'splide-custom-script', 'const splideSettingsPHP = ' . json_encode( array(
'uniqueTargetID' => $uniqueID,
'is_preview' => $is_preview,
'autoplay' => $autoplay,
) ), 'before' );
},
'keywords' => ['carousel', 'product', 'listing', 'ecommerce'],
'multiple' => false,
'reusable' => false,
'preview' => [
'image' => '', // Image ID
'title' => 'Carousel',
'description' => 'Carousel with product support',
],
'fields' => [
[
...
Hi Nick,
You can access the block ID via $attributes['id']
in the callback function or template.
https://docs.metabox.io/extensions/mb-blocks/#render_callback
And please notice that the ID of the block changes every time updating the post or refresh the editing page, be careful if you use the ID to style the element or use it as a selector.
In your case, I will inform the development team to consider supporting inline script in the template to execute JS functions.
Hi
Ok thanks, well I thought about using $attributes['id'] as it would work for my case; as its just for JS function purposes. It would be a useful if there was a way to pass the $attributes['id'] inside Javascript.
Thanks