Created
June 4, 2026 03:11
-
-
Save vapvarun/dc947b8d5ddb095fffa89c3e37657dcb to your computer and use it in GitHub Desktop.
WordPress shutdown action vs register_shutdown_function - tweakswp.com tutorial
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * WordPress shutdown action vs register_shutdown_function | |
| * | |
| * Demonstrates the two mechanisms for running code after WordPress | |
| * has finished processing. The 'shutdown' action fires within the | |
| * WordPress lifecycle; register_shutdown_function fires at PHP level | |
| * after output is flushed. | |
| * | |
| * Tutorial: https://tweakswp.com/ | |
| */ | |
| // --- Method 1: WordPress 'shutdown' action --- | |
| // Fires after the response is sent to the client (when using fastcgi_finish_request) | |
| // or just before PHP ends execution. Runs while WordPress objects are still in scope. | |
| add_action( 'shutdown', function () { | |
| // WordPress globals (wpdb, current_user, etc.) are still available here. | |
| // This is safe for database writes, cache operations, and cleanup tasks. | |
| error_log( '[shutdown action] WordPress shutdown action fired.' ); | |
| } ); | |
| // --- Method 2: PHP register_shutdown_function --- | |
| // Called by the PHP engine after the script finishes, including on fatal errors. | |
| // No WordPress context is guaranteed — use only when you need to catch fatal errors. | |
| register_shutdown_function( function () { | |
| $error = error_get_last(); | |
| if ( $error && in_array( $error['type'], [ E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR ], true ) ) { | |
| // Log the fatal error somewhere persistent. | |
| error_log( | |
| sprintf( | |
| '[fatal capture] %s in %s on line %d', | |
| $error['message'], | |
| $error['file'], | |
| $error['line'] | |
| ) | |
| ); | |
| } | |
| } ); | |
| // --- Key difference --- | |
| // WordPress 'shutdown' action: add_action( 'shutdown', $callback ) | |
| // - Runs inside WordPress lifecycle | |
| // - Has access to $wpdb, get_option(), wp_cache_*, WP_User, etc. | |
| // - Does NOT catch PHP fatal errors (script already dead) | |
| // | |
| // PHP register_shutdown_function( $callback ): | |
| // - Runs at PHP level after all output is done | |
| // - Catches E_ERROR (fatal), E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR via error_get_last() | |
| // - WordPress objects may not be fully available depending on when the fatal occurred |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment