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>
My Answer:
admin_post hook to handle the form submission and send the email. Here's the code I have so far:
php
// Add meta box with custom form and button
function custom_post_type_meta_box() {
add_meta_box(
'custom_email_meta_box',
'Send Email',
'custom_email_meta_box_callback',
'custom_post_type',
'normal',
'high'
);
}
add_action('add_meta_boxes', 'custom_post_type_meta_box');
function custom_email_meta_box_callback() {
?>
}
// Handle form submission
function send_email_callback() {
if (isset($_POST['action']) && $_POST['action'] == 'send_email') {
$post_id = $_POST['post_id'];
$post_title = get_the_title($post_id);
$to = 'admin@example.com';
$subject = 'New post published: ' . $post_title;
$message = 'A new post has been published on your site. Check it out!';
wp_mail($to, $subject, $message);
}
}
add_action('admin_post_send_email', 'send_email_callback');
Make sure to replace 'custom_post_type' with the name of your custom post type.
I hope this helps! Let me know if you have any questions.
Rate this post
5 of 5 based on 5845 votesComments