Search code examples
phpwordpressemailmessage

Send email once not every time post updated


I'm using "Front End PM" plugin and i have this snippet below for sending message to the post author when his post is published, it's working fine but still sending messages every time the post is updated! How can i stopped that?

Another point is how to send the same message to all registered users?

add_action( 'publish_post', 'fep_cus_user_publish_send_messaage', 10, 2 );

function fep_cus_user_publish_send_messaage( $ID, $post ){

    if ( ! function_exists( 'fep_send_message' ) )
    return;

    $message = [];

    $message['message_to_id'] = $post->post_author; // Post author ID. 
    $name = get_the_author_meta( 'display_name', $post->post_author );
    $title = $post->post_title;
    $permalink = get_permalink( $ID ); 
    $message['message_title'] = sprintf( 'Published: %s', $title );
    $message['message_content'] = sprintf ('Congratulations, %s! Your article “%s” has been published.', $name, $title );
    $message['message_content'] .= sprintf( 'View: %s', $permalink );
    $message['message_content'] .= sprintf( 'This is an automatic message, to let you know your post is published, and qualified for our quality standard!' );
    $override = array('post_author' => 1);//change with message sender id  


    // Send message
    fep_send_message( $message, $override );  

}

Solution

  • Use this Method :

     add_action( 'publish_post', 'fep_cus_user_publish_send_messaage', 10, 2 );
    
        function fep_cus_user_publish_send_messaage( $ID, $post ){
    
            if ( ! function_exists( 'fep_send_message' ) )
            return;
    
    
        //Check Send
        $send_email = get_post_meta( $post->ID, 'fep_send_email', true );
        if ( ! empty( $send_email ) ) return;
    
    
            $message = [];
    
            $message['message_to_id'] = $post->post_author; // Post author ID. 
            $name = get_the_author_meta( 'display_name', $post->post_author );
            $title = $post->post_title;
            $permalink = get_permalink( $ID ); 
            $message['message_title'] = sprintf( 'Published: %s', $title );
            $message['message_content'] = sprintf ('Congratulations, %s! Your article “%s” has been published.', $name, $title );
            $message['message_content'] .= sprintf( 'View: %s', $permalink );
            $message['message_content'] .= sprintf( 'This is an automatic message, to let you know your post is published, and qualified for our quality standard!' );
            $override = array('post_author' => 1);//change with message sender id  
    
        //Set Post Meta
        update_post_meta( $post->ID, 'fep_send_email', '1' );
    
            // Send message
            fep_send_message( $message, $override );  
    
        }