WordPress:页面发送后执行操作 [英] WordPress: Run an action after page sent

查看:90
本文介绍了WordPress:页面发送后执行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Wordpress博客中注册对某个帖子的所有访问.收集到的数据将发送到外部服务器,在该服务器上我将收集此博客和其他来源的信息.

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.

直到现在,我解决此问题的方法是使用钩子wp_footer,向远程服务器添加异步JSONP调用.但是这种方式会给生成的HTML增加一些开销,并且取决于用户是否启用了javascript.

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.

现在,我正在尝试做同样的事情,但是使用curl或任何类似的库通过php代码进行外部调用.这里的问题是增加页面生成时间的延迟,这可能会损害用户体验.发送内容并关闭HTTP连接后,有什么好的方法吗? WordPress钩子shutdown是否有效?

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?

推荐答案

这对我有用.请注意,如果您不想依赖WordPress配置,则PHP具有本机关闭功能.在send-server.com中,您可以执行以下操作:

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');

在external-server.com上的script.php中,您将拥有类似以下内容:

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

标头("HTTP/1.0 204 No Content");应该立即关闭连接,但脚本将继续执行.有关更多信息,请参见:从PHP发送HTTP请求而无需等待响应?

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?

这篇关于WordPress:页面发送后执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆