This is a timing issue, as you can see from the hook order. By the time you get to the dynamic_sidebar
function that executes your widget code on the front end, you are already past the widgets_init
and wp_enqueue_scripts
hooks (the dynamic_sidebar
hook is inside the function with that same name). You cannot enqueue scripts from a widget.
There are two ways to get around this:
- Write a function that accesses the widget data directly from the database (it’s a multidimensional array which you can find with
get_option(sidebars_widgets)
. You can bind this function to thewp_enqueue_scripts hook
. - In stead of properly enqueuing the script, just print it in the footer by using the
wp_footer
hook, which is still available when the widget code is executed.
By the way, wp_localize_script
will work anywhere, as it just prints the variables the moment it is called.