Amit

How to send bulk email to all users selecting user roles in wordpress without plugin

Here is the full code.

<div class="row">
	<?php if(isset($_POST['bulk_submit'])) {
	        $user_role = $_POST['user_role'];
	        $text_message = $_POST['text_message'];

	        $args = array (
	            'role' => $user_role,
	        );
	        $user_query = new WP_User_Query( $args );
	        $email_addresses = array();
	        foreach ( $user_query->results as $user ) {
	            $email_addresses[] = $user->user_email;
	        }
	        $to = $email_addresses;
	        $admin_email = get_option( 'admin_email' );
	        $subject = 'Admin Message';
	        $body = '<p><strong>Message:</strong> '.$text_message.'</p> ';
	        $headers = array('Content-Type: text/html; charset=UTF-8','From: '.$admin_email .'');
	        $sent =  wp_mail( $to, $subject, $body, $headers );
	        if($sent) {
	        echo "<h2>Email Successfully Sent</h2>";
	        }
	        else  {
	        echo "<h2>Failed</h2>";
	        }
	   } ?>
	    <form method="post" class="Individual-form mt-3 p-4">
            <div class="form-group">
                <select class="form-control" name="user_role" id="">
                    <option>-- select option --</option>
                    <option value="subscriber">Subscriber</option>
                    <option value="contributor">Contributor</option>
                    <option value="author">Author</option>
                    <option value="editor">Editor</option>
                    <option value="administrator">Administrator</option>
                </select>
            </div>
            <div class="form-group">
                <textarea name="text_message" class="form-control" id="" cols="30" rows="5" placeholder="Type You Message"></textarea>
            </div>
            <div class="form-group">
                <input class="btn btn-block btn-primary" name="bulk_submit" type="submit" value="Send Message">
            </div>
        </form>
</div>

Last Update on:March 5th, 2023 at 5:19 pm


How to Create a Custom Advanced Search form And Result Page in WordPress
Previous post