detect when shortcode ran for the last time

I’m wondering, given this code:

add_shortcode( $tag , $func );

Read More

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

Related posts

Leave a Reply

1 comment

  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.