如何使用wordpress ajax打开联系表单7

时间:2016-11-10 12:54:14

标签: ajax wordpress shortcode contact-form-7

我正在使用来自7插件的联系人,我的问题是通过wordpress admin ajax在弹出窗口中打开联系人表单7,但我的代码无效。只有弹出窗口打开但联系表单7没有提交。它在admin ajax url中重定向并返回0.

以下是我在functions.php中所做的代码

<?php
add_action('wp_head', 'my_action_popup_cf7_javascript');

function my_action_popup_cf7_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
    $('.myajaxcarrer').click(function(){
      //alert(1);
      var mydata = $(this).data();
      $(".overlay").fadeIn('slow');       
        var data = {
            action: 'my_action_popup_cf7',
            //whatever: 1234,
            id: mydata.id
        };
        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
        //console.log(ajaxurl);
        $('.item').removeClass('active');
        $('[data-id=' + mydata.id + ']').parent().addClass('active');
        $.post('<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php', data, function(response) {
           // alert('Got this from the server: ' + response);
           $('#testcarrer').html(response);
            var offset = $(window).scrollTop();

            $(".career-form").css("top", offset+50 );

            $('.closeBtn').click(function(e){
              e.preventDefault();
              $(".overlay").fadeOut('slow');
              $('.career-form').css("top", -1000+"%" )
            });
        });
    });
});

</script>
<?php
}

add_action('wp_ajax_my_action_popup_cf7', 'my_action_popup_cf7_callback');
add_action( 'wp_ajax_nopriv_my_action_popup_cf7', 'my_action_popup_cf7_callback' );

function my_action_popup_cf7_callback() {
     global $wpdb; // this is how you get access to the database
     //$whatever = 'ID=> '. $_POST['id'];
     //echo $whatever;
     ?>
     <a href="#" class="closeBtn">X</a>
      <h3>Apply Now</h3>
      <div class="formBox">
        <?php echo do_shortcode('[contact-form-7 id="905" title="My New Carrer Form"]'); ?>
      </div>
     <?php
     exit(); // this is required to return a proper result & exit is faster than die();
}

页面模板文件中的代码是

<span class="applyBtn"><a class="myajaxcarrer" data-id="903">Apply Now</a></span>

<div class="overlay"></div>
<div class="career-form">Ajax result Load here..</div>

js代码在下面。

$('.applyBtn').click(function(e){
  e.preventDefault();
  var offset = $(window).scrollTop();
  $(".overlay").fadeIn('slow'); 
  $(".career-form").css("top", offset+50 )
});

$('.closeBtn, .overlay').click(function(e){
  e.preventDefault();
  $(".overlay").fadeOut('slow');
  $('.career-form').css("top", -1000+"%" )
});

1 个答案:

答案 0 :(得分:0)

您可以通过回显do_shortcode('[带有ID的表单名称])打开它;它在你的php函数中。