在php请求之后不会调用操作

时间:2017-12-21 作者:murcoder

我想在用户填写完电子邮件表单后,通过mailchimp向用户发送一个下载链接。

PHP请求侦听器正在调用my_function(), 但在这个函数中the action is not called.

功能和操作正在运行。同样在放置do_action(); 内部createDownloadButton() 它将被称为。仅在将操作写入my_function() 这不管用?!

内部functions.php:

        /**
        * Place a button
        * @return string html-form
        * usage: [download_button download_name=\'my_download\']
        */    
        function createDownloadButton($atts ){
          //shortcode input
          $a = shortcode_atts( array(
              \'download_name\' => \'\'
          ), $atts );


            $result = \'<form class="form" method="post" action="\' . esc_url( $_SERVER[\'REQUEST_URI\'] ) . \'">\';
              $result .= \'<input hidden name="title" value="\'.$a[\'download_name\'].\'"  type="text" >\'; 

              $result .= \'<p>\';
               $result .= \'<input autofocus class="imput_mail" name="email" placeholder="email adress*" value="" type="email" required>\'; 
               $result .= \'<input class="bt" id="btn" onClick="ga(\\\'send\\\', \\\'event\\\', \\\'push_button\\\', \\\'some_analytics_event\\\');" value="" type="submit">\';
              $result .= \'</p>\';


          $result .= \'</form>\';
          return $result;
        }
        add shortcode(\'download_button\', \'createDownloadButton\' );



    /**
    *  PHP request listener
    */
    if( isset($_POST[\'email\']) && isset($_POST[\'title\']) ){
       my_function($_POST[\'email\'],$_POST[\'title\']);
    }


    /**
    *  Do some action here
    */
    function my_function($mail, $title){
     //echo works!
     echo "<script>console.log( \'email: ".$mail." | download: ".$title."\' );</script>"; 
     //why the action doen\'t work here?
     do_action(\'memberToMailchimpList\', \'<API-KEY>\', $mail, \'<LIST-ID>\', \'<INTEREST>\'); 
    }

1 个回复
最合适的回答,由SO网友:murcoder 整理而成

I just solved it!

问题是php request handling works different in wordpress.必须有一个解决方法admin_post.php hook:

而不是if( isset($_POST[\'email\']) && isset($_POST[\'title\']) ){...}

我不得不用这个钩子:

add_action( \'admin_post_nopriv_process_form\', \'process_form_data\' );
add_action( \'admin_post_process_form\', \'process_form_data\' );
function process_form_data() {
  my_function($_POST[\'email\'],$_POST[\'title\']);
  wp_redirect($_POST[\'url\']);
}
隐藏的表单字段用于钩住此函数。对于重定向,我在表单中创建了另一个隐藏字段,以将用户重定向回上一个站点:

  $current_url="//".$_SERVER[\'HTTP_HOST\'].$_SERVER[\'REQUEST_URI\'];
  //...
  $result .= \'<input type="hidden" name="url" value="\'.$current_url.\'">\'; //redirect
  $result .= \'<input type="hidden" name="action" value="process_form">\'; //hook
资料来源:adaptiveweb.com

结束