0

I would like to send an email to all editors of my blog when a new article has been published. I found many plugins but I want to solve this problem without plugins. In addition, I found a tutorial to send an email, but this is only for administrators of the blog but not for editors (Front-End Editor email notification issue). I would be happy if you could give me a tip or advice. Thank you.

<?php

function notifyauthor( $post_id ) {
    $post = get_post( $post_id );
    $author = get_userdata( $post->post_author ); // How can I specify the role of the editors here?
    $subject = "Post Published: " . $post->post_title;
    $message = ' Hi ' . $author->display_name . ',
    Your post, "' . $post->post_title . '" has just been published.
    View post: ' . get_permalink( $post_id ) . 'Thanks';

    wp_mail( $role->user_email, $subject, $message );
}

add_action( 'publish_post', 'notifyauthor' );
2
  • 1
    So you want to find a list of users by role so that you can loop through them and email them all? wordpress.stackexchange.com/q/219686/3276
    – Rup
    Commented Mar 25, 2019 at 12:37
  • Thanks for your answer. Yes exactly. All editors should receive an email when an amount has been published. Admins are excluded. Do you know how I can build the code?
    – sofarocker
    Commented Mar 25, 2019 at 12:44

1 Answer 1

1

Use get_users() function. Reference

function notify_editors( $post_id ) {
    $post = get_post( $post_id );

    // Get all editors
    $editors = get_users( [ 'role__in' => [ 'editor'] ] );

    foreach ( $editors as $editor ) {

        // Setup email
        $subject = "Post Published: " . $post->post_title;
        $message = ' Hi ' . $editor->display_name . ',
        Your post, "' . $post->post_title . '" has just been published.
        View post: ' . get_permalink( $post_id ) . 'Thanks';

        // and send...
        wp_mail( $editor->user_email, $subject, $message );
     }
}

add_action( 'publish_post', 'notify_editors' );  

You can read more here, about optional headers parameter that can add fields like from, cc, content-type etc.

1
  • That's excellent. Thank you very much.
    – sofarocker
    Commented Mar 26, 2019 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.