WordPress: Run an action after page sent

2019-07-18 20:47发布

I want to register all the visits to a certain post in a Wordpress blog. The collected data is sent to an external server where I gather the information of this blog and other sources.

Until now, my way of solving this problem was using the hook wp_footer, adding an asynchronous JSONP call to the remote server. But this way adds a little overhead to the generated HTML, and depends if the user has enabled javascript.

Now, I'm trying to do the same but making the external call through the php code, using curl or any similar library. The problem here is adding lag to the page generation time, that can penalize the user experience. Is there any good way of doing this after the content is sent and the HTTP connection closed? Would be the Wordpress hook shutdown valid?

1条回答
萌系小妹纸
2楼-- · 2019-07-18 21:21

This is what is working for me. Note that PHP has a native shutdown function if you don't want to be dependent on the WordPress configuration. From sending-server.com you could do something like this:

function do_php_shutdown_function(){
    //do your request here
    $param1 = urlencode($param1);
    $param2 = urlencode($param2);
    $request = "http://external-server.com/script.php?param1={$param1}&param2={$param2}";
    get_headers($request);
}
register_shutdown_function( 'do_php_shutdown_function');

In script.php on external-server.com you would have something like:

header("Access-Control-Allow-Origin: http://sending-server.com");
header("HTTP/1.0 204 No Content");
$param1 = urldecode($_GET['param1']);
$param2 = urldecode($_GET['param2']);
//do stuff

The header("HTTP/1.0 204 No Content"); should immediately close the connection yet the script will continue to execute. For more info see: Send HTTP request from PHP without waiting for response?

查看更多
登录 后发表回答