Site icon Hip-Hop Website Design and Development

Action hook "wp_insert_post" works but not for last imported post

I want to run a custom function whenever posts are imported to my custom post type.

I am currently running this code –

function on_post_import($post){
  global $wpdb;

  $results = $wpdb->get_results(
    "SELECT ID FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'"
  );

  foreach ($results as $result) {
      // run custom function
  }

  $wpdb->flush();
}
add_action( 'wp_insert_post', 'on_post_import' );

The problem I am facing is that it does not work for last imported post. So if there are 3 posts imported then it works fine for 2 of those posts but not for the 3rd one (last imported).

UPDATE: If there is only one post imported the custom function does not work.

UPDATE2: Seems like the issue is with my custom function which makes use of get_post_meta() which does not seem to output anything.

UPDATE 3: I am now simply using the wpdb query to run custom function. I want to avoid it as it will keep running in the background. If anyone have a better solution then do let me know thanks!

global $wpdb;

  $results = $wpdb->get_results(
    "SELECT ID FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'"
  );

  foreach ($results as $result) {
      // run custom function
  }

  $wpdb->flush();

What wrong am I doing? Or is there any other way to get my function to work on all imported posts including the last imported?