0

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.

  • I don't understand what you're trying to accomplish here. – Milo Dec 26 '15 at 18:53
  • Is it possible to add an action hook via wp_localise_script 'ng_slicknav_hook' => do_action( 'myplugin_after_hook'), – neilgee Dec 26 '15 at 20:48
0

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.

  • This almost works but what happens is that when reference it in my js file with ng_slicknav.ng_slicknav_hook it outputs null to the page and even I do not reference the hook in my js it is still output to the page and anything hooked to it - but not where I want it positioned. – neilgee Dec 30 '15 at 2:55
  • Is that a question or statement? – jgraup Dec 30 '15 at 3:00
  • it is what happens – neilgee Dec 30 '15 at 3:25
  • All the variables are attached to 'slickNavVars', what does that variable output? Localize script will just output before your JS so your JS has access to them. – jgraup Dec 30 '15 at 3:35
  • Yes sorry should have been more explicit above when I use slickNavVars.ng_slicknav.ng_slicknav_hook in my js it outputs null - but the hook also just outputs regardless if used in js or not – neilgee Dec 30 '15 at 3:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.