我用条件字段创建了多个CF7表单,我想使用Ajax在模式中显示它们。
我的选择列表允许我选择一个表单,然后通过do_shortcode使用它的值。
表单在模态中很好地显示,但是问题在于条件字段不正确。
我的问题是关于如何使此代码正常工作?
<?php
/**
* Plugin Name: YZ Bootstrap Modal
* Description: Show CF7 from in a modal.
* Version: 1.0
* Author: YZ
**/
if (!defined('ABSPATH')) {
exit;
}
add_action('wp_enqueue_scripts', 'yz_load_scripts');
function yz_load_scripts()
{
wp_enqueue_style('yz_modal', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
wp_enqueue_script("btpmin", 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js', array('jquery'), '', true);
}
add_action('wp_head', 'myplugin_ajaxurl');
function myplugin_ajaxurl() {
echo '<script type="text/javascript">
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
</script>';
}
function yz_add_bootstrap_modal()
{?>
<select id="selectList">
<option value="-1" selected>---</option>
<option value="172">Form1</option>
<option value="173">Form2</option>
<option value="174">Form3</option>
</select>
<script>
jQuery(document).ready(function($) {
$("#selectList").change(function(e) {
var formId = $(this).val();
$('#myModal').modal();
$.ajax({
url: ajaxurl,
data: {
id: formId,
action: "yz_form",
}
})
.done(function(response) {
if (response.success == true) {
$("#formContent").html(response.data.post_content);
$("div.wpcf7 > form").each(function(e) {
var $form = $(this);
wpcf7.initForm($form);
if (wpcf7.cached) {
wpcf7.refill($form);
}
});
}
});
});
});
</script>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<div id="formContent"></div>
<p><?php //echo do_shortcode('[contact-form-7 id="172"]') => works well?></p>
</div>
</div>
</div>
</div>
<?php }
add_action('wp_footer', 'yz_add_bootstrap_modal');
add_action('wp_ajax_nopriv_yz_form', 'yz_form');
add_action('wp_ajax_yz_form', 'yz_form');
function yz_form()
{
if (isset($_REQUEST["id"]) && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$form = do_shortcode('[contact-form-7 id="' . (int) $_REQUEST["id"] . '"]');
if (!is_wp_error($form)) {
wp_send_json_success(array('post_content' => $form));
} else {
wp_send_json_error();
}
wp_die();
}}