Reputation: 21
I've added a button in the backend of my custom post type editor.
I want to send an email using wp_mail()
when admin user click a button.
I've added this custom form and button to a meta box. See screenshot.
The problem is that when clicking this button Wordpress redirects to the default backend posts list page (https://mysite.test/wp-admin/edit.php).
I am making use of the do_action( "admin_post_{$action}" )
hook.
When I inspect the page I see Wordpress has removed the tags.
Any help will be greatly appreciated.
Here is my code:
<?php
$quote_add_meta_nonce = wp_create_nonce('send_quote_email_form_nonce');
add_action('admin_post_quote_email_pdf', 'quote_email_pdf');
function quote_email_pdf()
{
if (isset($_POST['send_quote_email_meta_nonce']) && wp_verify_nonce($_POST['send_quote_email_meta_nonce'], 'send_quote_email_form_nonce')) {
$emailMessage = '<h1>It works</h1>';
echo $emailMessage;
} else {
echo 'Something went wrong';
}
}
?>
<form action="<?php echo esc_url(admin_url('admin-post.php')); ?>" method="POST">
<input type="hidden" name="action" value="quote_email_pdf">
<input type="hidden" name="send_quote_email_meta_nonce" value="<?php echo $quote_add_meta_nonce ?>" />
<input type="submit" value="Email quote to customer" class="button">
</form>
Upvotes: 0
Views: 379
Reputation: 21
As mentioned in my comment, AJAX solved the problem.
Here is my updated code:
<?php
add_action('wp_ajax_quote_email_pdf', 'quote_email_pdf');
function quote_email_pdf()
{
wp_mail( $to, $subject, $message, $headers, $attachments );
die();
}
?>
<button class="button" id="downloadQuote">Send email</button>
<script>
jQuery(document).ready(function($){
const fullName = $('#quoteFullName').text();
const emailAddress = $('#quoteEmail a').text();
$('#downloadQuote').click(function(e){
e.preventDefault();
$.ajax({
url: sf_admin_ajax.sf_admin_ajax_url,
type: 'POST',
data: {
action: 'quote_email_pdf',
emailAddress: emailAddress,
fullName: fullName
},
beforeSend: function() {
$('.preloader-window').addClass('active')
},
success: function(data, textStatus, XMLHttpRequest) {
$('.preloader-window').removeClass('active')
console.log(data);
},
error: function ( MLHttpRequest, textStatus, errorThrown ) {
$('.preloader-window').removeClass('active')
console.log(errorThrown);
}
})
})
});
</script>
Upvotes: 0