add_action('wpcf7_before_send_mail')不会调用/挂钩我的函数

时间:2017-10-13 15:41:07

标签: php mysql wordpress contact-form-7

我正在尝试从我们的一个Contact7表单发布数据,然后将该数据保存在mysql表中。我是WordPress的新手。我跟着其他人的代码。但我没有运气在桌子上接收数据。我觉得add_action-wpcf7_before_send_mail无法挂钩我的函数,因为我在函数内部编写了错误拼写或错过的代码来测试它是否有效。但是,当我从wordpress表单提交数据时,没有错误显示。以下是我的代码,请评论任何可能有用的内容。谢谢!

add_action('wpcf7_before_send_mail','contactform7_before_send_mail',1);

function contactform7_before_send_mail( $contact_form ) {       
  $wpcf7_data->skip_mail = true;
  global $wpdb;   
  $title = $contact_form->title();   

  $submission = WPCF7_Submission::get_instance();
  if ( $submission ) {
    $formData = $submission->get_posted_data();     
  }

  if ( 'Membership-2' == $title ) {   
    $name = $formData['your-name'];     
    $email = $formData['your-email'];   
    $company = $formData['your-company'];   
    $title = $formData['your-title'];   
    $location = $formData['your-location']; 
  }

  $wpdb->insert('aoe84i5nxf_member_info', array('id' => null,'name' => $name,'email' => $email,'company' => $company,'title' => $title, 'location' => $location), array(null,'%s','%s','%s','%s','%d') ); 
}
remove_all_filters ('wpcf7_before_send_mail');

1 个答案:

答案 0 :(得分:0)

试试这个:

add_action('wpcf7_before_send_mail','contactform7_before_send_mail',1);

function contactform7_before_send_mail( $contact_form ) {       

    if ( !isset($contact_form->posted_data) && class_exists('WPCF7_Submission') ) {
        $submission = WPCF7_Submission::get_instance();
        if ( $submission ) {
            $formData = $submission->get_posted_data();     
        }
    } else {
        // We can't retrieve the form data
        return $contact_form;
    }

    if ( 'Membership-2' == $contact_form->title() ) {   
        $contact_form->skip_mail = true;

        $name = $formData['your-name'];     
        $email = $formData['your-email'];   
        $company = $formData['your-company'];   
        $title = $formData['your-title'];   
        $location = $formData['your-location']; 

        global $wpdb;
        $wpdb->insert('aoe84i5nxf_member_info', array('id' => null,'name' => $name,'email' => $email,'company' => $company,'title' => $title, 'location' => $location), array(null,'%s','%s','%s','%s','%d') ); 
    }

    return $contact_form;

}

对您的代码进行了一些更改:

  1. 检查我们是否可以检索表单提交数据。
  2. 更正了一些表单数据对象变量名称($ wpcf7_data)。
  3. 确保仅对Membership-2表单提交发生skip_mail和数据库插入。
  4. 删除remove_all_filters行 - 这只会取消挂起您的自定义函数,因此它永远不会运行。