Random ID for custom post type

the_ID()

must be within The Loop.

from the_ID codex page

global $post will merely get the last post that was set as the global post object which will depend greatly on what is done in the rest of the request. If somewhere in your header template, page template or content template you change or modify the global $post object that’s the one you will get back when you bring it into your function.