Add action hook into wp_localize_script

Is it possible to add an action hook via wp_localize_script, so I can position where I want the hook to run in HTML markup that is made in the JavaScript?

So something like:

$data = array (
    'ng_slicknav' = array(
        'ng_slicksearch'           = home_url( '/' ),
        'ng_slicknav_closedsymbol' = esc_html( $options['ng_slicknav_closedsymbol'] ),
        'ng_slicknav_hook'         = do_action( 'myplugin_after_hook' ),
    ),
);
// Add filter
$data = apply_filters( 'ng_slicknav_slickNavVars', $data );

// Pass PHP variables to jQuery script
wp_localize_script( 'slicknav-init', 'slickNavVars', $data );

wp_enqueue_script( 'slicknav-init' );

The variable I am trying to add is ng_slicknav_hook, but anything I hook to it falls just outside of the HTML markup in JavaScript; it doesn't honor the position I put it in.

Topic wp-localize-script actions hooks Wordpress

Category Web


Everything is working as expected. The problem is that your hook is rendering content to the page and you would like to pass that output to the javascript variable included in the JS output. You need to capture the hook output into a variable then add to $data.

// buffer output
ob_start();

   // run hook
   do_action('myplugin_after_hook');

// get the output buffer into a variable
$ng_slicknav_hook = ob_get_clean();

// add to data
$data = array(

    'ng_slicknav' => array(
        'ng_slicksearch'           => home_url('/'),
        'ng_slicknav_closedsymbol' => esc_html($options[ 'ng_slicknav_closedsymbol' ]),
        'ng_slicknav_hook'         => $ng_slicknav_hook,
    ),

);

It will most likely need to be escaped but I'll leave that to whatever content you're creating.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.