Skip to content

Instantly share code, notes, and snippets.

@eriktdesign
Created April 2, 2025 20:26
Show Gist options
  • Select an option

  • Save eriktdesign/30b47120e64d3bc204eddd6012de75e1 to your computer and use it in GitHub Desktop.

Select an option

Save eriktdesign/30b47120e64d3bc204eddd6012de75e1 to your computer and use it in GitHub Desktop.

Revisions

  1. eriktdesign created this gist Apr 2, 2025.
    41 changes: 41 additions & 0 deletions wrap-hook-actions-with-comments.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    <?php
    /**
    * Wraps output from functions attached to the wp_footer hook with HTML comments
    * Useful for finding stray bits of output. Save as an MU plugin and change the hook to whatever you want.
    */

    add_action( 'wp_footer', function() {
    echo '<!-- Start wp_footer -->' . "\n";
    global $wp_filter;

    if ( isset( $wp_filter['wp_footer'] ) && is_a( $wp_filter['wp_footer'], 'WP_Hook' ) ) {
    foreach ( $wp_filter['wp_footer']->callbacks as $priority => $callbacks ) {
    foreach ( $callbacks as $key => $callback ) {
    $original_callback = $callback['function'];

    // Wrap the original callback to output HTML comments before and after execution
    $wp_filter['wp_footer']->callbacks[ $priority ][ $key ]['function'] = function() use ( $original_callback ) {
    if ( is_array( $original_callback ) ) {
    $function_name = is_object( $original_callback[0] )
    ? get_class( $original_callback[0] ) . '->' . $original_callback[1]
    : $original_callback[0] . '::' . $original_callback[1];
    } elseif ( is_string( $original_callback ) ) {
    $function_name = $original_callback;
    } else {
    $function_name = 'Closure or anonymous function';
    }

    // Output HTML comment before execution
    echo "<!-- Before executing: $function_name -->\n";

    // Call the original callback
    call_user_func_array( $original_callback, func_get_args() );

    // Output HTML comment after execution
    echo "<!-- After executing: $function_name -->\n";
    };
    }
    }
    }
    echo '<!-- End wp_footer -->' . "\n";
    }, -9999 );