I'm trying to create an email alert every monday at midnight that will send the number of posts published the past week on the site.

I created 2 variables: $post_published_to_date which is the total count of the posts on the site (I assumed here that the site was just created to there aren't any posts yet) and $published_posts which is the number of posts published during the past week.

I used date('D', $timestamp) === 'Mon' && $timestamp = strtotime('midnight')in the if statement to find out if it's monday at midnight. If it is, an email is sent to the admin with the number of posts published.

I'm not sure is setting $published_posts to 0 at the end will work well, and I'm afraid $post_published_to_date will be reset to 0 each time. I'm beginning in Php so I'm not really sure here.

    $post_published_to_date = 0;
    $published_posts = wp_count_posts()->publish;

    if(date('D', $timestamp) === 'Mon' && $timestamp = strtotime('midnight')) { 
    $post_published_to_date = $post_published_to_date + $published_posts;

    add_action( 'publish_post', 'number_of_posts_published', 10 ,2 );
    function number_of_posts_published( $ID, $post, $published_posts; ) {
        if ( 'post' !== $post->post_type)

        $to = 'admin@mysite.com'
        $subject = 'Number of posts last week';
        $headers = array('Content-Type: text/html' );
        $message = '<h3> Hello ! </h3> <p>  

        Last week, $published_posts posts were published on your site. ';

        wp_mail( $to, $subject, $message, 'Content-Type: text/html' ); 

    $published_posts = 0; 


Would this work as expected ? Would you advise any modification that are better practices ?

Thanks for your time and help

  • Why not get a count from a query that only pulls posts published within the past 7 days?
    – jdm2112
    Dec 8 '15 at 17:58
  • That's probably a very good idea but I don't know how to do this ... Would you have a few minutes to help me out ? Thanks for your answer and help Dec 8 '15 at 19:43

Here is a basic use for WP_Query that returns an object containing all posts for the current week as $query. The last line echos the property `found_posts', which provides the count for the week query.

    $args = array(
        'date_query' => array(
                'year' => date( 'Y' ),
                'week' => date( 'W' ),
    $query = new WP_Query( $args );
    echo $query->found_posts;

For your purposes, I do not know if the week is based on an empirical calendar or if this is based on your site's Settings > General > date settings.

With a little testing you should be able to produce reliable results for your email each week. https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters

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.