0

I'm looking for php code that will allow me to do the following: when new post publish in categories which ids are 12 and 34, email will send to all users.

2

You can use transition_post_status function, then fetch users and send an email to all users.

Here is a sample code, it's not tested. But it will get you started with this.

function wcs_send_mail_on_publish_category_posts( $new_status, $old_status, $post ) {

    global $post;

    if ( 'publish' !== $new_status or 'publish' === $old_status ) return;

    if ( in_category( array( '12', '34' ) ) ) {

        $subscribers = get_users( array ( 'role' => 'subscriber' ) );
        $emails      = array ();

        foreach ( $subscribers as $subscriber )
            $emails[] = $subscriber->user_email;

        $body = sprintf( 'Hey there is a new entry! See <%s>', get_permalink( $post )  );

        wp_mail( $emails, 'New entry!', $body );

    }

}

add_action( 'transition_post_status', 'wcs_send_mail_on_publish_category_posts', 10, 3 );
  • In real life it is not as easy. First thing is that you might not want to send an email when the post is updated (gone draft and the published again). More important is that if you have many users your email is likely be blocked by your hosting or marked as spam by anti spam services. – Mark Kaplun Sep 24 '14 at 7:21
  • Yes, that's the downside. I think he should use Feedburner, mailchimp or similar service to email subscribers. – Robert hue Sep 24 '14 at 7:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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