0

I'd like to send an automated review email to the site admin whenever a post has been published for more than 12 months.

I've tried using the following code but can't seem to get it to work, or perhaps it's that I'm not entirely sure where I would put it or how I would call it???

Any help would be greatly appreciated.

//send review email to admin
function post_review_notification() {
    $old_post = 60*60*24*365;
    $site_title = get_bloginfo( 'name' );
    $to = get_option('admin_email');
    $subject = .$site_title .'- Please review' .$post->post_title;
    $message = 'This post is over 12 months old, please update or retire '."\n".'Post Title: ' .$post->post_title. "\n"."Visit the post: " . get_permalink( $post->ID );
    
   if((date('U')-get_the_time('U')) > $old_post) {
        wp_mail( $to, $subject, $message );
      }
      else {
      }
}

1 Answer 1

2

You ask a good question, where I would put it or how I would call it? I don't think you want to loop over all the posts everytime somebody visiting your site checking if any of them are more than one year old. Here is some thoughts about how this could be realized.

Assume you have a function to send a reminder about a post:

function send_reminder( $post_id ) {
    if ( get_post_status( $post_id ) == 'publish' ) {
        $post_data = get_post( $post_id );
        // send a reminder about the post
    }
}

You can use a wp_schedule_single_event function of WP Cron to schedule notification in a year when a new post gets published:

add_action('publish_post', 'add_reminder');
function add_reminder( $post_id ) {
    wp_schedule_single_event( time() + 60*60*24*365, 'send_reminder', array( $post_id ) );
}

However this action would run every time when a post gets any update. I don't know what is the best approach, read this Q/A for more information. Maybe using a transition_post_status hook would be better.

And now you need to add such a scheduled action to every post already published on your site. You need to use custom WP_Query loop over all the published posts and add a scheduled event for every one of them. This operation should be done only once, all new posts would have a reminder added via add_reminder function. The best approach I could think of is to do all of this as a plugin and put this loop inside a function that would be triggered on a plugin activation.

1
  • Thanks for the advice Ivan, and for pointing me toward some helpful resources. I'll give this a go and see if I can get it to work. Commented Oct 15, 2020 at 3:13

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.