Skip to content

Instantly share code, notes, and snippets.

@AnadarProSvcs
Created November 26, 2023 23:23
Show Gist options
  • Save AnadarProSvcs/389cda3c26281063f62fb72d91d1bc91 to your computer and use it in GitHub Desktop.
Save AnadarProSvcs/389cda3c26281063f62fb72d91d1bc91 to your computer and use it in GitHub Desktop.
Sending an Email When New Posts Are Added in WordPress
// Hook to the post insertion action, to trigger a notification on certain post types
add_action('wp_insert_post', 'notify_admin_for_new_post', 10, 3);
function notify_admin_for_new_post($post_id, $post, $update)
{
// Check for a specific custom post type and if the post is being published for the first time
if ($post->post_type == 'custom_post_type' && $post->post_status == 'publish' && empty(get_post_meta($post_id, 'check_if_run_once'))) {
// Initialize variables
$organizer = '';
$post_title = get_the_title(); // Assuming it's the title of the post
$event_date = '';
$location = '';
$date_published = get_the_date();
$categories = get_the_terms(get_the_ID(), 'custom_taxonomy');
// Retrieve post meta
$meta = get_post_meta(get_the_ID());
if (isset($meta)) {
// Process organizer information if available
$organizer_ids = $meta['custom_organizer_meta_key'];
if (isset($organizer_ids)) {
$organizer = html_entity_decode(get_the_title($organizer_ids[0]));
} else {
$organizer = 'Not Found';
}
// Process event date information if available
$event_date_info = $meta['custom_date_meta_key'];
$event_date = isset($event_date_info) ? $event_date_info[0] : "Not Found";
// Process location information if available
$location_id = $meta['custom_location_meta_key'];
$location = isset($location_id) ? html_entity_decode(get_the_title($location_id[0])) : "Not Found";
}
// Compose the subject and message of the email
$subject = 'Notification - New Post - ' . $organizer;
$message = 'A new post has been published.';
// ... (construct the rest of the message)
// Send the email
$to = get_bloginfo('admin_email');
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail($to, $subject, $message, $headers);
// Update the post meta to prevent this notification from running again
update_post_meta($post_id, 'check_if_run_once', true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment