How to Automatically Notify Your Members on New Posts

Home » Snippets » How to Automatically Notify Your Members on New Posts
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you looking for a way to automatically notify your website members whenever new posts are published? Keeping your members engaged and informed is crucial for any website, especially those focused on WordPress and web development. In this article, we will explore how you can easily set up automated notifications to ensure that your members never miss out on the latest content. Say goodbye to manual notifications and hello to increased member engagement. Let’s dive in!

					function wpturbo_notify_members_on_new_post($post_id) {
    $post = get_post($post_id);
    $members = get_users(['role' => 'subscriber']);
    
    foreach ($members as $member) {
        wp_mail($member->user_email, 'New Post Notification', 'A new post titled "' . $post->post_title . '" has been published.');
    }
}
add_action('publish_post', 'wpturbo_notify_members_on_new_post');
				

The code snippet provided in this article allows you to automatically notify your members whenever a new post is published on your WordPress website.

Let’s go through the code step by step to understand how it works.

First, we define a function called wpturbo_notify_members_on_new_post which takes the $post_id as a parameter. This function will be responsible for sending notifications to all the subscribed members.

In the next line of code, we use the get_post() function to retrieve the post object based on the given $post_id. This is necessary to access the title of the newly published post.

Next, with the help of the get_users() function, we retrieve an array of all the users who have the role of "subscriber". These are the members who will receive the notification when a new post is published.

Now comes the loop. Using a foreach loop, we iterate through each member in the $members array.

Inside the loop, we use the wp_mail() function to send an email notification to each member. The function takes three parameters: the recipient’s email address, the subject of the email (which in this case is "New Post Notification"), and the body of the email.

In the body of the email, we use concatenation to include the title of the newly published post by accessing the post_title property of the $post object.

Finally, we add the action publish_post with the callback function wpturbo_notify_members_on_new_post to the add_action() function. This ensures that the wpturbo_notify_members_on_new_post function is executed whenever a post is published.

By adding this code to your WordPress website, you will be able to automatically notify your members via email whenever a new post is published.

Register an account to save your snippets or go Pro to get more features.