2017-04-05 30 views
0

我很惊讶为什么wp_verify_nonce无法正常工作。它显示未定义的函数错误,我的wordpress版本是最新的。我附上我的插件代码。请帮我wp_verify_nonce不工作,而wp_create_nonce工作

add_shortcode('tw_safety_checklist_template','init_tw_safety_checklist'); 

    function init_tw_safety_checklist(){ 
     echo '<form method="post"> 
      <label>Name</label> 
      <input type="hidden" name="tw_new_checklist_nonce" value="'.wp_create_nonce('tw_new_checklist_nonce').'"/> 
      <input type="text" name="tw_name" /> 
      <input type="submit" name="submit" value="Submit"/> 
     </form>'; 
    } 

    if(isset($_POST['tw_new_checklist_nonce'])){ 
     tw_create_my_template();    
    } 

    function tw_create_my_template(){ 
     if(wp_verify_nonce($_POST['tw_new_checklist_nonce'],'tw-new-checklist-nonce')) 
     { 
      return 'Worked!'; 
     } 
    } 

回答

2

问题是wp_verify_nonce()pluggable功能。这意味着直到加载插件后才会声明它。由于您的文件中的if声明松散,因此当您的插件加载时它将被执行;因此,wp_verify_nonce()(正确)尚未申报。

您需要使用add_action()将您的if声明转换为action hook。哪个钩子将取决于你的tw_create_my_template()函数的目的是什么。你会想要做这样的事情:

add_action('init','tw_create_my_template'); 
function tw_create_my_template(){ 
    if(isset($_POST['tw_new_checklist_nonce']) 
     && wp_verify_nonce($_POST['tw_new_checklist_nonce'],'tw-new-checklist-nonce')) 
    { 
     return 'Worked!'; 
    } 
} 

注意,你会想与任何挂钩是适合您的功能,以取代initinit对于插件初始化操作相当典型,但重要的是它发生在plugins_loaded之后。您可以按顺序找到典型操作列表,here

+0

嗨,谢谢你的回复!它工作完美 – user3783411