I want to update My Wordpress Post right after publishing the Post?

Viewed 27

I want to update My WordPress Post right after publishing the Post. The code given below updates the post but my dashboard keeps loading until timeout error. I want to add some more content after the post is created.

function updatemypost( $post_id, $post,$update ) {
            
    $mydata = array(
        'ID' => $post_id,
        'post_content' => 'New Data..',
    );
         
    wp_update_post( $mydata );

}
add_action( 'publish_post', 'updatemypost', 10, 3 );
1 Answers

The publish_post fires every time you update a post not only when it's first published, so you're ending up with an inifine loop.

You can fix it by removing the action before firing update_post like this

function updatemypost( $post_id, $post,$update ) {
        
    $mydata = array(
      'ID' => $post_id,
      'post_content' => 'New Data..',
    );
    
    remove_action( 'publish_post', 'updatemypost', 10 );
    wp_update_post( $mydata );
    add_action( 'publish_post', 'updatemypost', 10, 3 );
       
}
add_action( 'publish_post', 'updatemypost', 10, 3 );
Related