Created
June 4, 2026 03:11
-
-
Save vapvarun/c0030b6fcbd37f24a7595b245cf23f5b to your computer and use it in GitHub Desktop.
Send data to external API after response is complete using WordPress shutdown - 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 | |
| /** | |
| * Sending data to an external API after the response is complete | |
| * | |
| * Uses fastcgi_finish_request() to flush output to the browser, then | |
| * fires the WordPress 'shutdown' action to POST data to an external | |
| * endpoint without blocking the user's page load. | |
| * | |
| * Tutorial: https://tweakswp.com/ | |
| */ | |
| /** | |
| * Queue a payload to POST to an external API on shutdown. | |
| * | |
| * @param string $endpoint Full URL of the external API endpoint. | |
| * @param array $payload Data to send as JSON. | |
| */ | |
| function tweakswp_send_after_response( string $endpoint, array $payload ): void { | |
| add_action( | |
| 'shutdown', | |
| static function () use ( $endpoint, $payload ) { | |
| // Flush output to the browser if FastCGI is available. | |
| // After this call, the user's browser receives the complete response | |
| // and the connection is closed. PHP continues executing. | |
| if ( function_exists( 'fastcgi_finish_request' ) ) { | |
| fastcgi_finish_request(); | |
| } | |
| // Do NOT use wp_remote_post() here — it respects WP_HTTP_BLOCK_EXTERNAL | |
| // and depends on hooks that may have already fired. Use a direct cURL call. | |
| $ch = curl_init( $endpoint ); | |
| curl_setopt_array( $ch, [ | |
| CURLOPT_POST => true, | |
| CURLOPT_POSTFIELDS => wp_json_encode( $payload ), | |
| CURLOPT_RETURNTRANSFER => true, | |
| CURLOPT_TIMEOUT => 10, | |
| CURLOPT_HTTPHEADER => [ | |
| 'Content-Type: application/json', | |
| 'Accept: application/json', | |
| ], | |
| ] ); | |
| $result = curl_exec( $ch ); | |
| $status = curl_getinfo( $ch, CURLINFO_HTTP_CODE ); | |
| curl_close( $ch ); | |
| if ( WP_DEBUG ) { | |
| error_log( sprintf( '[shutdown API] %s → HTTP %d', $endpoint, $status ) ); | |
| } | |
| }, | |
| 10 | |
| ); | |
| } | |
| // Usage example: send a conversion event after a WooCommerce order is placed. | |
| add_action( 'woocommerce_thankyou', function ( int $order_id ) { | |
| $order = wc_get_order( $order_id ); | |
| if ( ! $order ) { | |
| return; | |
| } | |
| tweakswp_send_after_response( | |
| 'https://analytics.example.com/v1/events', | |
| [ | |
| 'event' => 'purchase', | |
| 'order_id' => $order_id, | |
| 'total' => $order->get_total(), | |
| 'currency' => $order->get_currency(), | |
| 'user_email' => $order->get_billing_email(), | |
| ] | |
| ); | |
| } ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment