By default, get_users()
returns the users for the current blog only. You can make that more clear by setting the argument blog_id
:
$users = get_users( array ( 'blog_id' => $GLOBALS['blog_id'] ) );
But that shouldn’t be needed.
Now, combining the codes from Execute function when post is published and Multiple recipients for wp_mail()
, we can use something like this:
Get the email addresses
function get_notify_emails( $post, $blog_id = NULL )
{
if ( NULL === $blog_id )
$blog_id = $GLOBALS[ 'blog_id' ];
$users = get_users( array ( 'blog_id' => $blog_id ) );
if ( empty ( $users ) ) // something went wrong
return array ();
$recipients = array ();
$from = '';
foreach ( $users as $user )
{
// set sender
if ( isset ( $user->caps[ 'administrator' ] )
&& '1' === $user->caps[ 'administrator' ]
&& '' === $from
)
{
$from = "{$user->data->display_name} <{$user->data->user_email}>";
continue;
}
// exclude super admins
if ( is_super_admin( $user->ID ) )
continue;
// exclude post author
if ( (int) $post->post_author === (int) $user->ID )
continue;
// add the other users as recipients
$recipients[] = "{$user->data->display_name} <{$user->data->user_email}>";
}
return ( array ( $from, $recipients ) );
}
Send the emails
add_action( 'transition_post_status', 'notify_blog_users_on_new_posts', 10, 3 );
function notify_blog_users_on_new_posts( $new_status, $old_status, $post )
{
if ( 'publish' !== $new_status or 'publish' === $old_status )
return;
$post_types = get_post_types( array ( 'publicly_queryable' => TRUE ) );
if ( ! in_array( $post->post_type, $post_types ) )
return;
list ( $from, $to ) = get_notify_emails( $post );
$subject = 'New post on ' . get_bloginfo( 'name' ) . ': ' . get_the_title( $post );
$headers = array ( "from:$from" );
$message = 'Hello,
there is a new post on our blog:
' . get_the_title( $post ) . '
<' . get_permalink( $post->ID ) . '>
Enjoy!';
wp_mail( $to, $subject, $message, $headers );
}
This is just a draft, it needs some tests, and I would probably separate the code into multiple, specialized classes. But it should give an idea how to proceed.