Вот что я получил: на WordPress, используя подписки woocommerce, у пользователей есть возможность отказаться от подписки на странице своей учетной записи. Прямо сейчас, когда они нажимают кнопку отмены, подписка просто отменяется без какого-либо подтверждения или раздумий. Я хочу, чтобы, когда они нажимают кнопку отмены, открывался модуль обратной связи с несколькими переключателями. Как только они выбирают вариант переключателя, он отображает кнопку отмены, а затем, когда они нажимают кнопку отмены, он делает две вещи: 1) отправляет электронное письмо администратору с параметром переключателя, который они выбрали, и 2) отменяет их подписку.
Я просмотрел весь Интернет, пытаясь понять это, и я не могу на всю жизнь заставить его работать. Я чувствую, что я действительно близок, но не могу понять, как запустить оба действия. Я могу запустить одно или другое действие, но не оба. Я запускаю все это на локальном хосте, используя Bitnami, и я также не очень знаком с Javascript и Ajax, которые, как я знаю, должны будут работать. Большую часть кода ниже я взял из Интернета, так что извините, если он кажется разобранным вместе.
Я также пытался отправить электронное письмо, когда пользователь нажимает переключатель, а затем кнопка отмены просто была действием, но я столкнулся с проблемой, когда страница обновлялась каждый раз, когда они нажимали переключатель. Теперь, если бы я мог отправить электронное письмо и не обновлять страницу, этот способ сработал бы, однако это менее желательный способ. :)
Таким образом, любая помощь будет высоко оценена! :)
Ниже приведен код, который у меня сейчас есть:
PHP для электронной почты
if (isset($_POST['radio'])){
$user_info = get_userdata(1);
$email = $user_info->user_email;
$to = "[email protected]";
$from = "[email protected]";
$subject = "Subscription Cancelled";
$message = "Reason for unsubscribing: " . $_POST['radio'] . "\nName: " .
$user_info->last_name . ", " . $user_info->first_name . "\nUser Email: ". $email;
$headers = "From:" . $from;
wp_mail($to,$subject,$message,$headers);
}
var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.querySelector(".close-button");
function toggleModal() {
modal.classList.toggle("show-modal");
}
function windowOnClick(event) {
if (event.target === modal) {
toggleModal();
}
}
trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
function show1() {
document.getElementById('button').style.display = 'inline-block';
}
function show2() {
document.getElementById('button').style.display = 'inline-block';
}
window.addEventListener("DOMContentLoaded", function() {
var form = document.getElementById("contact");
document.getElementById("submit_button").addEventListener("click", function() {
form.submit();
});
});.modal {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(101, 101, 101, 0.5);
opacity: 0;
visibility: hidden;
transform: scale(1.1);
transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
}
.modal-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
padding: 1em 1.5em;
width: 95%;
max-width: 510px;
}
.modal-content #button {
margin-top: 15px;
text-align: right;
}
.modal-content span.radio {
width: 100%;
display: block;
padding: 5px 0;
}
.close-button {
top: 2px;
position: absolute;
right: 10px;
font-size: 1.4em;
cursor: pointer;
color: #949494;
font-weight: 600;
}
.close-button:hover {
color: #333333;
}
.show-modal {
opacity: 1;
visibility: visible;
transform: scale(1.0);
transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}
.reveal-if-active {
opacity: 0;
max-height: 0;
overflow: hidden;
font-size: 16px;
transform: scale(0.8);
transition: 0.5s;
}
label {
display: block;
margin: 0 0 3px 0;
}
input[type = "text"] {
width: 100%;
}
.modal-content ul {
margin-left: 0;
}
.modal-content ul li {
display: block;
position: relative;
float: left;
width: 100%;
}
.modal-content ul li input[type=radio] {
position: absolute;
visibility: hidden;
}
.modal-content ul li label {
display: block;
position: relative;
font-weight: 300;
font-size: 1em;
padding: 10px 25px;
margin: 5px auto;
cursor: pointer;
-webkit-transition: all 0.25s linear;
background: #f5f5f5;
border-left: 3px solid #949494;
}
.modal-content ul li .check {
display: block;
position: absolute;
border: 2px solid #AAAAAA;
border-radius: 100%;
height: 12px;
width: 12px;
top: 21px;
left: 10px;
z-index: 5;
transition: border .25s linear;
-webkit-transition: border .25s linear;
}
.modal-content ul li .check::before {
display: block;
position: absolute;
content: '';
border-radius: 100%;
height: 4px;
width: 4px;
top: 2px;
left: 2px;
margin: auto;
transition: background 0.25s linear;
-webkit-transition: background 0.25s linear;
}
.modal-content input[type=radio]:checked~.check {
border: 2px solid #428bca;
}
.modal-content input[type=radio]:checked~.check::before {
background: #428bca;
}
.hide {
display: none;
}
.form {
margin-bottom: 0;
}<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class = "trigger button cancel">Cancel Subscription</a>
<div class = "modal">
<div class = "modal-content">
<form id = "contact" action = "" method = "post">
<span class = "close-button">×</span>
<h3>Title</h3>
<p>Description:</p>
<ul>
<li>
<input type = "radio" name = "radio" id = "option1" value = "option 2" onclick = "show1();" /><label for = "option1">Option 1</label>
<div class = "check"></div>
</li>
<li>
<input type = "radio" name = "radio" id = "option2" value = "option 2" onclick = "show2();" /><label for = "option2">Option 2</label>
<div class = "check"></div>
</li>
</ul>
<div id = "button" class = "hide">
<a id = "submit_button" onclick = "document.getElementById('contact').submit();" href = "<?php echo esc_url($action['url']); ?>" class = "unsubscribe-button button cancel">Submit and Cancel Subscription 2</a>
</div>
</form>
</div>
</div>


![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


ОБНОВЛЕНИЕ: я наконец-то заставил этот код работать! Я исправил ошибки, а также включил ссылку на самый последний файл jquery. Самая важная часть, которую я сделал, это инициировала WP в файле unsubscribe-email.php. Как только я добавил код include '../../../../wp-load.php'; в файл, все действительно начало складываться.
Окончательный JS
jQuery(document).ready(function($){
$('#submit_button').click(function(){
var radio = $("input[name='radio']:checked").val();
var email = $("input[name='user_email']").val();
var first = $("input[name='first_name']").val();
var last = $("input[name='last_name']").val();
var emailData = {
'radio' : radio,
'user_email' : email,
'first_name' : first,
'last_name' : last,
};
$.ajax ({
type: 'POST',
url: '/unsubscribe-email.php',
data: emailData,
success: function() {console.info('Ajax Success');},
error: function() {console.info('Ajax Error');},
statusCode: {
200: function() {console.info('200 Everything ok!');},
400: function() {console.info('400 Bad request');},
403: function() {console.info('403 Forbidden');},
500: function() {console.info('500 Server Error');}
}
});
});
});
Окончательный адрес электронной почты.php
include '../../../../wp-load.php';
$radio = $_POST['radio'];
$email = $_POST['user_email'];
$to = "[email protected]";
$from = "[email protected]";
$subject = "Subscription Cancelation";
$message = "Name: " . $_POST['first_name'] . " " . $_POST['last_name'] . "\nEmail: ". $email . "\nReason: " . $radio;
$headers .= 'FROM:' . $from . "\r\n" . 'Reply-To:' . $email;
if (wp_mail($to,$subject,$message,$headers)) {
http_response_code(200);
} else {
http_response_code(500);
}
Окончательный HTML
<a class = "trigger button cancel">Cancel Subscription</a>
<div class = "modal">
<div class = "modal-content">
<form id = "contact" action = "<?php $current_status = $subscription->get_status();
$subscription_id = $subscription->get_order_number();
$subscription_url = $subscription->get_view_order_url();
$cancel_url = $subscription_url . '?subscription_id=' . $subscription_id . '&change_subscription_to=cancelled';
$cancel_subscription_url = wp_nonce_url( $cancel_url, $subscription_id . $current_status );
if ( $current_status == 'active' || $current_status == 'on-hold' || $current_status == 'pending' ) {
echo $cancel_subscription_url ; } ?>" method = "post" name = "contact" style = "margin-bottom: 0;">
<?php $user_info = wp_get_current_user(); ?>
<input type = "hidden" value = "<?php echo $user_info->user_email ?>" name = "user_email" />
<input type = "hidden" value = "<?php echo $user_info->first_name ?>" name = "first_name" />
<input type = "hidden" value = "<?php echo $user_info->last_name ?>" name = "last_name" />
<h3>We're Sorry to See You Go!<span class = "close-button"><i class = "far fa-times-circle"></i></span></h3>
<div class = "options">
<ul>
<li>
<input type = "radio" name = "radio" id = "option1" value = "option 1" />
</li>
<li>
<input type = "radio" name = "radio" id = "option2" value = "option 2" />
</li>
<li>
<input type = "radio" name = "radio" id = "option3" value = "option 3" />
</li>
</ul>
<div id = "button" class = "hide">
<input id = "submit_button" type = "submit" name = "submit" value = "Submit and Cancel Subscription" />
</div>
</div>
</form>
</div>
</div>