Post variables not displaying correctly in custom function

The insideds of a function is separated from the global things. Therefore the variables, set by other processes are not reachable/useable inside a function until you made them so, with, for example global keyword for a var.

So

Add

the_post();

after the function’s {,

or add

global $post;

and use $post->ID instead of the_ID and so on.
I also recommend you to read some books on programming PHP.