Support » Developing with WordPress » publish_post hook trigger twice when I publish post

  • I am trying to send email post content on post publish and written small function in functions.php but it fires twice I am getting same mail 2 times. I am using wordpress version 5.2.2. Please find code below:

    function send_members($ID, $post)  {
       global $wpdb;
       if( ! ( wp_is_post_revision($post->ID) || wp_is_post_autosave($post->ID) ) ) {
    	$cat = get_the_category($post->ID);
    	    if($cat[0]->cat_ID = 40){
               $tableusers = $wpdb->prefix.DB_TABLE_BTC_MLM_USERS;
               $users = '';
               $subject = $post->post_title;
    	   $body = $post->post_content;
    	   wp_mail($users, $subject, strip_tags($body));
    add_action('publish_post', 'send_members',10,2);
Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz


    It’s a little known fact that many hooks fire more than once per request. It often goes unnoticed because saving additional data or whatever multiple times does no harm and leaves no trace. It’s reasonable to assume all hooks fire more than once. If that’s a problem for your code, you must take measures to ensure your callback only does its thing once per request no matter how many times it’s called.

    One way to do so is have the callback remove itself from the action stack when it is finished with its task. Add this just before the return statement:
    remove_action('publish_post', 'send_members', 10 );

    Hi @bcworkz

    Thanks for your reply.
    I already checked your post about remove_action but unfortunately, it’s not working. Do you have any other suggestions on this topic?


    Moderator bcworkz


    You could set a global variable after sending the email. Before sending any email, check for this global and do not mail if it has been set. Thus mail will be sent only once per request even if the action fires 100 times in one request.

    So do I.

Viewing 4 replies - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.