WordPress: Run an action after page sent

泪湿孤枕 提交于 2020-01-15 03:45:05

问题


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:


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?



来源:https://stackoverflow.com/questions/16120482/wordpress-run-an-action-after-page-sent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!