Custom loop isnt working correctly

This custom function would work except for the fact that when I am updating the post, it takes the “external-client-id” value for the CURRENT post and doubles it.

What I want it to do is to find the HIGHEST value (hence the ‘while’ loop) and double THAT.

It seems like $check_client_id = get_post_meta( $post_id, 'wpcf-external-client-id', true ); is the culprit.

Any advice on how to correctly implement this?

function set_external_client_id( $post_id, $post, $update ) {
	
	if ( 'auction-client' == $post->post_type ) {
	 if( $update ){
            $args = array(  
                'post_type' => 'auction-client',
                'post_status' => 'publish',
                );
            $myloop = new WP_Query( $args ); 
            
            //loop through all posts of this post type to find the highest client id
            $find_highest_id = 0;
            while ( $myloop->have_posts() ) : $myloop->the_post();
                $check_client_id = get_post_meta( $post_id, 'wpcf-external-client-id', true );
                if( $check_client_id > $find_highest_id ){
                    $find_highest_id = $check_client_id;
                }
            endwhile;
            
            wp_reset_postdata();

            //take the highest value from the custom loop and double it
            $external_client_id = $find_highest_id * 2;
            update_post_meta( $post_id, 'wpcf-external-client-id', $external_client_id);
         }
	}
}
add_action( 'wp_insert_post', 'set_external_client_id', 10, 3 );



Source link