Print-Clearly

Browse Site

Get WordPress to send comment alerts

Do you ever wish that your WordPress plugin let you know when someone’s left a comment on your site? I run this script on a cron job which runs hourly and does exactly that…

    require_once('../wp-config.php'); // this gets the database settings

    $check_interval = new DateTime();

    // you may need to change this next line to your cron job interval
    date_modify($check_interval, '-1 hour'); 
    $db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    $sql = "SELECT * FROM wp_comments ;
    $sql .= "WHERE comment_date >= '".$check_interval->format('Y-m-d H:i:s')."'")";

    $result = $db->query($sql);

    if ($result)
    {
        $alert_text = '';

        while ($row = $result->fetch_object())
        {
            $alert_text.= '<p><strong>'.$row->comment_author.'</strong>';
            $alert_text.= '<br />'.$row->comment_content;
            $alert_text.='</p>';
        }

        $headers  = "Content-Type: text/html; charset=iso-8859-1\n";
        $headers .= "From: From Address <my@email.com>\n";
        $headers .= "X-Mailer: PHP4\n";
        $headers .= "X-Priority: 3\n";
        $headers .= "\n";

        $mail_body = "<html><head></head><body>";
        $mail_body .= $alert_text;
        $mail_body .="</body></html>";

        mail('my@email.com', 'WordPress Post Alert', $mail_body, $headers);
    }

Once the script is run it checks any comments with a timestamp between ‘now’ and the interval time in the past, and should there be results from this then it lists them all in an e-mail and sends them my way.

Now all I need to do is moderate them.

This entry was posted in Blog, Blogging, Geeky Stuff, php, Web.

Comments are closed.