I'm wondering, given this code:

add_shortcode( $tag , $func );

Is there a hook I can use that will always be called AFTER the last time $func was called, but soon enough, so I can still call wp_localize_script()?

WP Function referencres: add_shortcode, wp_localize_script

1 Answer 1


Not sure about the last time, but you can hijack every shortcode and either call wp_localize_script() here or register an action for wp_footer that runs earlier than the footer script handler.

Let’s say, this is the original:

add_shortcode( 'foo', 'original_function' );

Now you can overwrite it with:

add_shortcode( 'foo', 'new_function' );

function new_function( $atts, $content = '', $shortcode_name )
    wp_localize_script( 'my_handle', $data );

    // alternative: register a callback for wp_footer
    add_action( 'wp_footer', 'localize_my_script', -2 );

    return original_function( $atts, $content = '', $shortcode_name );

Related, with a longer example: Use AJAX in shortcode

Update in response to your comment

Catching all arguments for the gallery shortcode is even easier:

add_filter( 'post_gallery', 'collect_gallery_args', 10, 2 );

function collect_gallery_args( $empty, $args )
    // store $args somewhere, then

    add_action( 'wp_footer', 'localize_my_script', -2 );

    return $empty;

See wp-includes/media.php.

  • Thanks, add_action('wp_footer', 'my_in_between_function'); did the trick! really cool that you managed to give me the solution I needed despite the vagueness of my question. +2 for you!
    – Jules
    Apr 30, 2013 at 21:04
  • @Jules It was not a completely new problem. I have added a link to an example to my answer that might be useful for you.
    – fuxia
    Apr 30, 2013 at 21:08
  • not really, but upvoted anyway :) My problem was a bit more simple. Just kind of difficult to explain. The problem was that I have written a plugin that replaces the native WP gallery with a fancy javascript based gallery. Problem was, since multiple instances of [gallery] are possible, that I wanted to save all the parameters for all the galleries in single array. And only if ALL the HTML for the galleries was generated, pass that array to my javascript in one simple variable instead of a variable with a generated name for each gallery. Hope I make sense :)
    – Jules
    Apr 30, 2013 at 21:16
  • @Jules Next time, add such details to your question please. :) I made an update to my answer with a more specific solution.
    – fuxia
    Apr 30, 2013 at 23:07

Your Answer

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

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