Try adding global $post;
to the function, so that the $post
variable will be available within the function’s scope. Also, make sure your code is executing inside The Loop. If the function is executing too early, then $post
may not be available.
If neither of those things work, please post the full function and any other relevant code or details.