我正在使用AJAX创建Mailchimp订阅表单,以避免在表单提交时重新加载PHP页面。
这是我到目前为止所得到的:
MailChimp.php
包装器的格式如下:https://github.com/drewm/mailchimp-api
sm_mailchimp.php
我的代码至今为止如下:
<?php
include('MailChimp.php'); // path to API wrapper downloaded from GitHub
use \DrewM\MailChimp\MailChimp;
function sm_mailchimp_subscribe()
{
$mcAPIKey = 'e7bab977bb31af5709e3889eec2d4eb4-us19';
$mcListID = '02da2478bd';
$MailChimp = new MailChimp($mcAPIKey);
$email = $_POST['mailchimp-email'];
$fname = $_POST['mailchimp-fname'];
$sname = $_POST['mailchimp-sname'];
$merge_vars = array(
'FNAME' => $fname,
'SNAME' => $sname
);
$result = $MailChimp->post("lists/" . $mcListID . "/members", [
'email_address' => $email,
'merge_fields' => $merge_vars,
'status' => 'subscribed',
]);
return json_encode($result);
}
function sm_mailchimp_form_shortcode($atts)
{
$action = site_url() . "/wp-admin/admin-ajax.php";
$form = '
<form action="' . $action . '" name="sm_mailchimp" method="post" id="sm_mailchimp" class="sm_mailchimp">
<input type="text" name="fname" id="mailchimp-fname" placeholder=" First Name">
<input type="text" name="sname" id="mailchimp-sname" placeholder="Last Name">
<input type="email" name="mailchimp-email" id="mailchimp-form" placeholder="Email">
<button type="submit">SIGN UP</button>
</form>
';
return $form;
}
add_shortcode('sm_mailchimp', 'sm_mailchimp_form_shortcode');
function sm_mailchimp_enqueue_scripts()
{
wp_register_script('sm-mailchimp-js', get_stylesheet_directory_uri() . '/sm_mailchimp/sm_mailchimp.js', array('jquery'), '1.0', true);
wp_localize_script('sm-mailchimp-js', 'ajax_obj', array('ajax_url' => get_stylesheet_directory_uri() . '/sm_mailchimp/sm_mailchimp.php'));
wp_enqueue_script('sm-mailchimp-js');
}
add_action('wp_enqueue_scripts', 'sm_mailchimp_enqueue_scripts');
sm_mailchimp.js
最后是实现AJAX的JS代码
jQuery(function($) {
$(document).ready(function() {
// From wp_localized
const ajaxURL = ajax_obj.ajax_url;
console.log("TCL: ajaxURL", ajaxURL);
$("#sm_mailchimp").submit(function() {
var form = $(this);
$.ajax({
url: ajaxURL,
type: "POST",
data: form.serialize(),
success: function(data) {
console.log(data);
}
});
return false;
});
});
});
在控制台上出现以下错误:
Fatal error: Uncaught Error: Call to undefined function add_shortcode() in /Users/stefanomonteiro/Local Sites/real-homes/app/public/wp-content/themes/realhomes-child/sm_mailchimp/sm_mailchimp.php on line 43
编辑:如果我将短代码和入队功能删除到function.php
,console.log将不返回任何内容。