简体   繁体   中英

WordPress: wp_mail function only works once in foreach loop

I'm running a cron with a function to delete old events (based on a custom field). The function works find and deletes all events which lie in the past. So far so good...

Now I want to send an email to the author of the event, that the event has been deleted. I'm doing this with an extra wp_mail function inside a foreach.

The problem now is, that only the last of the old events gets deleted. Maybe this has somesthing to do with the variables for the mail ( $post , $author , ...) inside the foreach?

I read something about that issue here but I don't understand it: wp_mail() in a loop, only sending to last address

Here is my code:

function get_delete_old_events() {

    $past_query = date('Y-m-d', strtotime('-1 day'));

    // Set our query arguments
    $args = [
        'fields'         => 'ids', // Only get post ID's to improve performance
        'post_type'      => 'event', // Post type
        'posts_per_page' => -1,
        'meta_query'     => [
            [
                'key'     => 'gid_22', // Replace this with the event end date meta key.
                'value'   => $past_query,
                'compare' => '<='
            ]
        ]
      ];
    $q = get_posts( $args );

    // Check if we have posts to delete, if not, return false
    if ( !$q )
        return false;

    // OK, we have posts to delete, lets delete them
    foreach ( $q as $id )

        /* start e-mail  */
            $headers[] = 'From: SITENAME <hello@domain.com>';

            $post       = get_post($id);
            $author     = get_userdata($post->post_author);
            $subject    = "SUBJECT: ".$post->post_title."";

            $message = "THE MESSAGE BODY";

            wp_mail($author->user_email, $subject, $message, $headers);
        /* end e-mail */

        wp_trash_post( $id );
}

// expired_post_delete hook fires when the Cron is executed
add_action( 'old_event_delete', 'get_delete_old_events' );


// Add function to register event to wp
add_action( 'wp', 'register_daily_events_delete_event');

function register_daily_events_delete_event() {
    // Make sure this event hasn't been scheduled
    if( !wp_next_scheduled( 'old_event_delete' ) ) {
        // Schedule the event
        wp_schedule_event( time(), 'hourly', 'old_event_delete' );
    }
}

wp_mail function returns bool (See Wordpress Documentation here ). So, it exits the function as it returns the value in it's first iteration.

Just add a variable before the wp_mail

 $is_sent = wp_mail($author->user_email, $subject, $message, $headers);

It should work then.

Try below code.

function get_delete_old_events() {
    $past_query = date('Y-m-d', strtotime('-1 day'));
    // WP_Query arguments
    $args = array(
        'fields'         => 'ids', // Only get post ID's to improve performance
        'post_type'      => array( 'event' ), //post type
        'posts_per_page' => '-1',//fetch all posts,
        'meta_query'     =>array(
                                    'relation'  => 'AND',
                                    array(
                                            'key' => 'gid_22',
                                            'value' =>  $past_query,
                                            'compare'   => '<='
                                          )
                                  )
        );

    // The Query
    $query = new WP_Query( $args );

    // The Loop
    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
            // do something
            $headers[] = 'From: SITENAME <hello@domain.com>';

            $postid     = get_the_ID();
            $post       = get_post($postid);
            $author     = get_userdata($post->post_author);
            $subject    = "SUBJECT: ".get_the_title()."";

            $message = "THE MESSAGE BODY";

            wp_mail($author->user_email, $subject, $message, $headers);
            wp_trash_post( $id );
        }
    } else {
        // no posts found
        return false;

    }

    // Restore original Post Data
    wp_reset_postdata();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM