Sometimes you need a custom submit box within your WordPress admin, not only to save updated data, but to also run a custom function. In our example below we will send an email to a specified email address but you can run any custom code.

First off you need the code below to add the custom button to the post page. We recommend simply adding this code to the bottom of your functions.php.

/**
* Create the Send Email button in the post edit screen
*
* @param WP_Post $post
* @return void
*/
function blz_add_email_button_to_post( $post ){
    // Checking its the correct post type
    if ( get_post_type( $post ) == 'post' ){
        echo '<div class="email-buttons"><input id="send-email" class="button-primary" name="send-email" type="submit" value="Send Email" /></div>';
    } 
} 
add_action('post_submitbox_minor_actions', 'blz_add_email_button_to_post', 10 );

Now you need to add the code below to check if it was this button that was pushed, and if so, send the email.

/** 
 * Check if we're requesting that the email be sent during the Save request 
 * 
 * @param integer $post_ID
 * @param WP_Post $post
 * @param boolean $update
 * @return void
 *  */ 
function blz_check_if_send_email_button_pushed(int $post_ID, WP_Post $post, bool $update){ 
    if ( key_exists( 'send-email', $_POST ) && $_POST['send-email'] == 'Send Email'){ 
        $to = 'sendto@example.com'; 
        $subject = 'The subject'; 
        $body = 'The email body content'; 
        $headers = array('Content-Type: text/html; charset=UTF-8'); 
        wp_mail( $to, $subject, $body, $headers );
    } 
} 

add_action( 'save_post', 'blz_check_if_send_email_button_pushed', 10, 3 );

That’s it! Now when you push your custom button in the post editor it will send an email. Note that you can use this for custom post types by changing the post type its checking for in the top snippet and changing the add action line to the code below for the second snippet where {$post->post_type} is the slug of your post type.

add_action( 'save_post_{$post->post_type}, 'blz_check_if_send_email_button_pushed', 10, 3 );
Scroll to Top