我正在开发一个使用AJAX的插件,但我在控制代码流方面遇到了困难。
我想在运行条件后挂接函数。我的钩子在控制结构内部添加时不会启动,但在外部会启动。
我还有一个触发AJAX请求的事件,这只能在用户点击触发事件后,在加载所有DOM之后发生。AJAX请求告诉PHP函数设置cookie。它设置了cookie,但在阅读关于cookie的PHP文档时,我发现它们只能在发送任何输出后设置,但我还是做到了这一点?
我读过WordPress初始化序列,但这并没有帮助我解决这个问题。
这是我的密码:
add_action(\'wp_head\', \'Init_\');
function Init_(){
if(isset($_COOKIE[\'user_opt\'])){
$user_opt = $_COOKIE[\'user_opt\'];
if($user_opt === \'out\'){
function user_checkout(){
$ch_script_url = plugins_url(\'/js/check_out.js\', __FILE__);
wp_enqueue_script(\'checkout\', $ch_script_url);
}
add_action(\'wp_enqueue_scripts\', \'user_checkout\'); // load this if the cookie is set
}
} else { // run this otherwise
function user_opt_handler(){
$opt_script_url = plugins_url(\'/js/opt_handler.js\', __FILE__);
wp_enqueue_script(\'opt_handler\', $opt_script_url, array(\'jquery\'), TRUE);
$nonce = wp_create_nonce(\'my_nonce\');
$ajax_url = admin_url(\'admin-ajax.php\');
wp_localize_script(
\'opt_handler\',
\'options\',
array(
\'check\' => $nonce,
\'ajax_url\' => $ajax_url
)
);
}
function opt_box_html(){ ?>
<div id="user-opt-box">
<button id="user-choice-yes">Yes</button> <!-- the AJAX in the "opt_handler" script will fire when an click event for this button happens -->
</div>
<?php }
function user_handler(){
if(is_admin() === TRUE){
check_ajax_referer(\'my_nonce\');
setcookie(\'user_opt\', \'out\');
wp_die();
}
}
add_action(\'wp_enqueue_scripts\', \'user_opt_handler\');
add_action(\'wp_footer\', \'opt_box_html\', 100);
add_action(\'wp_ajax_user_handler\',\'user_handler\');
add_action(\'wp_ajax_nopriv_user_handler\', \'user_handler\');
}
}
我还注意到,当使用普通(在所有函数之外)范围内的php变量时,挂钩函数无法访问它。例如,尝试执行此操作时:
$a = "hello world";
function my_func(){
echo $a;
}
add_action(\'wp_footer\', \'my_func\');
这将输出NULL
. 这是因为wordpress挂钩只能访问其中声明的变量吗?