0

I'm using this code to try loading some custom assets for a custom post type I have registered

    public function setup_theme_backend_assets($hook)
    {
        $screen = get_current_screen();        
        if( in_array( $hook, ['post.php', 'post-new.php']) ){
            if( is_object( $screen ) && 'store-locator' == $screen->post_type ){
                wp_register_script(
                    'map',
                    'https://unpkg.com/[email protected]/dist/leaflet.js',
                    [],
                    false,
                    true
                );
                wp_enqueue_script('map');

                wp_register_script( 
                    'map-config', 
                    plugin_dir_url(__FILE__) . '/inc/leaflet-map.js', 
                    [], 
                    false, 
                    true 
                );
                wp_enqueue_script('map-config');

                wp_register_style(
                    'map',
                    'https://unpkg.com/[email protected]/dist/leaflet.css',
                    false
                );
                wp_enqueue_style('map');
            }
        }
    }

To call the function into the class construct I'm using this hook

add_action('admin_enqueue_scripts', [$this, 'setup_theme_backend_assets']);

I've noticed using the chrome dev tools that the assets aren't loaded, is there something wrong into my function?

11
  • as an aside, I would avoid using the CDN's for leaflet, as it's a privacy and performance problem! In the old days when you used a CDN for a library it would allow you to make an extra connection to speed it up, then cache it for all sites, but modern browsers have independent caches for every site so there's no speed up, and it's a performance hit as you can't use HTTP2 parallel transfers to download the file either
    – Tom J Nowell
    Mar 10, 2023 at 9:33
  • @ICTDEV, I don't think this will work - $hook != 'edit.php?post_type=store-locator' - because the value of that $hook is likely edit.php regardless the current post type. So maybe you would want to use if ( 'edit-store-locator' !== get_current_screen()->id ) instead.
    – Sally CJ
    Mar 10, 2023 at 9:50
  • @SallyCJ ok, need to test, as I write into another comment, I'm trying to load leaflet map inside a metabox of a custom post type
    – ICTDEV
    Mar 10, 2023 at 10:26
  • If you're trying to target the post editing screen (e.g. at wp-admin/post.php), then that edit-store-locator would be store-locator. But the point here is check the current screen ID.
    – Sally CJ
    Mar 10, 2023 at 10:32
  • @SallyCJ ok, I've noticed that I had a typo also into the code, now I'm able to see that the css of leaflet is loaded, but the js files ssems not present and no map will be displayed. Need to fix this
    – ICTDEV
    Mar 10, 2023 at 10:44

0

Your Answer

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