Pass PHP vars to gutenberg sidebar

Question

I tried to pass PHP vars to my gitenberg sidebar, but the js object value is always null.

I use the following code to register my js inside a class :

add_action( 'init', array($this,'sidebar_plugin_register') );
add_action( 'enqueue_block_editor_assets', array($this,'sidebar_plugin_script_enqueue') );

With the functions :

function sidebar_plugin_register() {
        wp_register_script(
            'sidebar-js',
            plugins_url( 'js/editor-sidebar.js', __FILE__ ),
            array( 'wp-plugins', 'wp-edit-post', 'wp-element' )
        );
}     
function sidebar_plugin_script_enqueue() {
        wp_enqueue_script( 'sidebar-js');
        $data = array(
            'var1'            => 'test',
            'var2' => __( 'demo', 'default' )
        );
        wp_localize_script( 'sidebar-js', 'sidebardata', $data );
}

And the content of my editor-sidebar.js file is :

( function( wp ) {
    var registerPlugin = wp.plugins.registerPlugin;
    var PluginSidebar = wp.editPost.PluginSidebar;
    var el = wp.element.createElement;
    
    console.log( sidebardata );

    registerPlugin( 'manager-for-icomoon', {
        render: function() {
            return el( PluginSidebar,
                {
                    name: 'my-plugin-sidebar',
                    icon: 'admin-post',
                    title: 'My plugin sidebar',
                },
                'Info'
            );
        },
    } );
} )( window.wp );

The sidebar is working but console.log( sidebardata ) is sending null on console…

Can anybody help me ?

Thanks

0
Albedo0 3 months 0 Answers 10 views 0

Leave an answer