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() {
            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',
    } );
} )( window.wp );

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

Can anybody help me ?


  • What are the values you're trying to pass? There's an extremely high chance that the approach you've chosen is unnecessary and can be avoided by either accessing the data store in JS, or using register_meta, some more context for what you're trying to do that needs this would be super helpful ( it looks like you asked how to implement your solution to a problem, rather than how to solve the original problem, then made your question too generic )
    – Tom J Nowell
    Commented Nov 6, 2020 at 16:53
  • I use PHP to parse a CSS file to extract a list of class and i want to send it to my sidebar. Perhaps it's not the better solution, but it should work...
    – Albedo0
    Commented Nov 6, 2020 at 16:59


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.